d1 = [{'del':True, 'Name':'tbl_n','node':'3'},{'del':True, 'Name':'src_n','node':'5'}]
d2 = [{'items':'23', 'column_name':'tbl_n','created':'3.34','count':0,'valid':'yes'},
{'items':'43', 'column_name':'src_n','created':'3.34','count':40,'valid':'yes'},
{'items':'22', 'column_name':'mod_n','created':'3.34','count':13,'valid':'no'}
我想将d1与d2合并为d1中的'Name'键和d2中的'column_name'
下面的是尝试过的步骤之一
from collections import Counter
summed = sum((Counter({elem['column_name']: elem['val_count']}) for elem in my_dict1 + my_dict2), Counter())
print(summed)
我想要的预期输出是
d3 = [{'items':23, 'Name': 'tbl_n','node':3,'created':3.34,'count':0,'valid':'yes'},{'del':True,'items':43,'Name':'src_n','node':5.'created':3.34,'count':40,'valid':'yes'},{'items':22,'column_name:'mod_n','created':3.34,'count':14,'valid':'no'}
答案 0 :(得分:0)
我试图了解您的预期输出并建议您使用以下解决方案。告诉我你是否还有别的想法。关于您的代码,我将d1
和d2
标识符分别替换为ld1
和ld2
('ld'代表'字典列表')以提高可读性:
ld1 = [{'del':True, 'Name':'tbl_n','node':'3'},
{'del':True, 'Name':'src_n','node':'5'}]
ld2 = [{'items':'23', 'column_name':'tbl_n','created':'3.34','count':0, 'valid':'yes'},
{'items':'43', 'column_name':'src_n','created':'3.34','count':40,'valid':'yes'},
{'items':'22', 'column_name':'mod_n','created':'3.34','count':13,'valid':'no'}]
def mergeTwoListOfDicts(ld1, ld2):
result = []
for d2 in ld2:
for d1 in ld1:
if ('Name' in d1) and ('column_name' in d2):
if d1['Name'] == d2['column_name']:
d2.pop('column_name')
d2.update(d1)
break
result.append(d2)
return result
print(mergeTwoListOfDicts(ld1, ld2))
# [{'items': '23', 'created': '3.34', 'count': 0, 'valid': 'yes', 'del': True, 'Name': 'tbl_n', 'node': '3'},
# {'items': '43', 'created': '3.34', 'count': 40, 'valid': 'yes', 'del': True, 'Name': 'src_n', 'node': '5'},
# {'items': '22', 'created': '3.34', 'count': 13, 'valid': 'no', 'column_name': 'mod_n'}]