[英]what is the best way to add element to list of dict in python?
我有两个字典列表,例如:
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_list 和 b_list 可能是一个很长的列表。
谢谢!
对于更大的列表,您可以执行以下操作:
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)
Output
[{'file_path': '/test/test.gz', 'is_upload': False, 'key': 1, 'md5': '65d28'},
{'file_path': '/test/test2.gz', 'is_upload': True, 'key': 2, 'md5': '800cc9'}]
如果要就地修改a_list
,请执行以下操作:
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)
您可以使用这个高效的代码(使用one-loop ):
for i in range(len(a_list)):
if a_list[i]['key'] == b_list[i]['key'] and a_list[i]['md5'] == b_list[i]['md5']:
a_list[i]['is_upload'] = b_list[i]['is_upload']
Output:
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.