python - 比较列相等时如何追加列
问题描述
我有两个列表需要根据两者中存在的列名进行合并。源是 JSON。我不知道该怎么做,我看了如何用相同的键合并多个字典?但那不限制任何东西。
例子:
dict1 = {"a": 3, 'b': 4}
dict2 = {"a": 3, 'c': 5}
dict3 = {"a": 1, 'b': 2}
dict4 = {"a": 1, 'c': 8}
dict_result = [{"a": 3, 'b': 4, 'c': 5},{"a": 1, 'b': 2, 'c': 8}]
BR
解决方案
这里试试这个。
dict1 = {"a": 3, 'b': 4}
dict2 = {"a": 3, 'c': 5}
dict3 = {"a": 1, 'b': 2}
dict4 = {"a": 1, 'c': 8}
def merge_dictionary(*args):
dictionary = []
dict_result=[]
app_index = 0 # append index
for dic in (args):
for item, value in dic.items():
if [item, value] not in dictionary:
dictionary.append([item, value])
for index, x in enumerate(dictionary):
if index%3==0:
dict_result.append({x[0]:x[1]})
app_index = index
else:
dict_result[app_index//3].update({x[0]:x[1]})
return dict_result
print(merge_dictionary(dict1, dict2, dict3, dict4))
推荐阅读
- ruby-on-rails - 出于测试目的,尝试从一个 actionmailer 方法返回所有已发送电子邮件的数组
- opencv - 如何获得干净的视差图和干净的深度图
- javascript - 如何使用 Vanilla JavaScript 或 JQuery 实现受控组件(在 ReactJS 中)
- file - 上传文件到 Telegram Server 的方法
- ruby-on-rails - 如果只配置了一个主机,Rails 是否会自动找出 MongoDB 副本集中的主节点?
- java - 解决此错误错误,找不到符号方法 makeHttpRequest(String,String,List
) - google-cloud-platform - 使用 AI Platform 将图像分割模型部署到生产环境:HTTP 请求 500 错误
- reactjs - 关于firebase + react的教程有问题
- php - PHP 致命错误:“无法在写入上下文中使用函数返回值”
- matplotlib - 如何为 Seaborn 条形图指定不确定性条?