Python:合并两个字典列表 [英] Python: Merge two lists of dictionaries
本文介绍了Python:合并两个字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> lst1 = [{id:1,x:one},{id:2,x:two}]
>>> lst2 = [{id:2,x:two},{id:3,x:three}]
>>> merge_lists_of_dicts(lst1,lst2)#通过id键#merge两个字典项列表
[{id:1,x:one},{id:2,x:two},{id :3,x:three}]
任何方式实现 merge_lists_of_dicts
根据字典项目的键合合两个字典列表
解决方案
code> lst1 = [{id:1,x:one},{id:2,x:two}]
lst2 = [{id :2,x:two},{id:3,x:three}]
result = []
lst1.extend(lst2 )
在lst1中的myDict:
如果myDict不在结果中:
result.append(myDict)
打印结果
输出
[{' x':'one','id':1},{'x':'two','id':2},{'x':'three','id':3}]
Given two lists of dictionaries:
>>> lst1 = [{id: 1, x: "one"},{id: 2, x: "two"}]
>>> lst2 = [{id: 2, x: "two"}, {id: 3, x: "three"}]
>>> merge_lists_of_dicts(lst1, lst2) #merge two lists of dictionary items by the "id" key
[{id: 1, x: "one"}, {id: 2, x: "two"}, {id: 3, x: "three"}]
Any way to implement merge_lists_of_dicts
what merges two lists of dictionary based on the dictionary items' keys?
解决方案
lst1 = [{"id": 1, "x": "one"}, {"id": 2, "x": "two"}]
lst2 = [{"id": 2, "x": "two"}, {"id": 3, "x": "three"}]
result = []
lst1.extend(lst2)
for myDict in lst1:
if myDict not in result:
result.append(myDict)
print result
Output
[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]
这篇关于Python:合并两个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文