在python中,向dict列表添加元素的最佳方法是什么?
我有两张清单,比如:在python中,向dict列表添加元素的最佳方法是什么?,python,database,list,dictionary,Python,Database,List,Dictionary,我有两张清单,比如: a_list = [ {'key': 1, 'md5': '65d28', 'file_path': '/test/test.gz'}, {'key': 2, 'md5': '800cc9', 'file_path': '/test/test2.gz'} ] b_list = [ {'key': 1, 'md5': '65d28', 'is_upload': False}, {'key': 2, 'md
a_list = [
{'key': 1, 'md5': '65d28', 'file_path': '/test/test.gz'},
{'key': 2, 'md5': '800cc9', 'file_path': '/test/test2.gz'}
]
b_list = [
{'key': 1, 'md5': '65d28', 'is_upload': False},
{'key': 2, 'md5': '800cc9', 'is_upload': True}
]
我必须得到如下结果:
a_list = [
{'key': 1, 'md5': '65d28', 'file_path': '/test/test.gz', 'is_upload': False},
{'key': 2, 'md5': '800cc9', 'file_path': '/test/test2.gz', 'is_upload': True}
]
最有效的方法是什么
我的第一个代码是:
for a in a_list:
for b in b_list:
if a['key'] == b['key'] and a['md5'] == b['md5']:
a['is_upload'] = b['is_upload']
break
但如果不使用双循环,是否有更有效的方法?原因a_列表和b_列表可能是一个长列表
谢谢大家! 对于较大的列表,您可以执行以下操作:
a_dict = {(ai['key'], ai['md5']): ai for ai in a_list}
b_dict = {(bi['key'], bi['md5']): bi for bi in b_list}
result = [{**value, **b_dict.get(key, {})} for key, value in a_dict.items()]
print(result)
输出
[{'file_path': '/test/test.gz', 'is_upload': False, 'key': 1, 'md5': '65d28'},
{'file_path': '/test/test2.gz', 'is_upload': True, 'key': 2, 'md5': '800cc9'}]
如果要就地修改列表,请执行以下操作:
您可以使用此高效代码(使用单循环):
范围内的i(len(a_列表)):
如果a_列表[i]['key']==b_列表[i]['key']和a_列表[i]['md5']==b_列表[i]['md5']:
a_列表[i]['is_upload']=b_列表[i]['is_upload']
输出:
a_list=[{'key':1,'md5':'65d28','file_path':'/test/test.gz','is_upload':False},
{'key':2,'md5':'800cc9','file_path':'/test/test2.gz','is_upload':True}]
列表是否总是排序(…或者您可以先排序)?-在这种情况下,您可以同时对两个列表进行迭代,并每次选择词汇值最低的列表(如果它们相同,则在插入之前将它们合并到单个dict)。如果两个条目中都存在相同的键,那么它可能只是第一个列表中idx的第二个列表中的索引查找(即,对于idx,a_list.enumerate()中的元素:…b_list[idx]…
b_dict = {(bi['key'], bi['md5']): bi for bi in b_list}
for d in a_list:
d.update(b_dict.get((d['key'], d['md5']), {}))
print(a_list)