我有一本这种格式的字典:
{
'a': ([1,2,3],[-1,-2,-3]),
'b': ([1,2,3],[-1,-2,-3]),
'z': ([],[-1])
}
还有一个:
{
'a': ([4,5],[]),
'c': ([1,2,3],[-4]),
'z': ([],[-3])
}
我想将它们都合并为这种格式:
{
'a': ([1,2,3,4,5],[-1,-2,-3]),
'b': ([1,2,3],[-1,-2,-3]),
'c': ([1,2,3],[-4]),
'z': ([],[-1,-3])
}
我将如何去做?我对Python也很陌生,我想知道这是否是表示数据的最佳方法,是否应该使用某种数据结构代替字典。
答案 0 :(得分:2)
尝试一下:
d1 = {'a': ([1,2,3],[-1,-2,-3]),'b': ([1,2,3],[-1,-2,-3]),'z': ([],[-1])}
d2 = {'a': ([4,5],[]),'c': ([1,2,3],[-4]),'z': ([],[-3])}
d3 = {}
d4 = {**d1, **d2} # This will work for Python 3.5+
for k in d4:
if k in d2 and k in d1:
tm = (d1[k][0]+ d2[k][0], d1[k][1]+d2[k][1])
d3[k] = tm
elif k in d2 and k not in d1:
d3[k] = d2[k]
else:
d3[k] = d1[k]
输出:
d3 = {'a': ([1, 2, 3, 4, 5], [-1, -2, -3]), 'b': ([1, 2, 3], [-1, -2, -3]), 'z': ([], [-1, -3]), 'c': ([1, 2, 3], [-4])}
答案 1 :(得分:1)
您可以使用处理合并的帮助器功能将此问题分为两个步骤。
dict1 = {
'a': ([1,2,3],[-1,-2,-3]),
'b': ([1,2,3],[-1,-2,-3]),
'z': ([],[-1])
}
dict2 = {
'a': ([4,5],[]),
'c': ([1,2,3],[-4]),
'z': ([],[-3])
}
def ordered_list_merge(lst1, lst2):
'''
Merges two lists, and does not add duplicates from lst2 into lst1
'''
resulting_list = lst1.copy() #to ensure list 1 is not mutated by changes to resulting_list
resulting_list.extend(x for x in lst2 if x not in resulting_list)
return resulting_list
import copy
result_dict = copy.deepcopy(dict1) #to ensure result_dict is an entirely new object, and mutations on result_dict do not affect dict1
for k, v in dict2.items():
if k not in result_dict:
result_dict[k] = v
else:
result_dict[k] = tuple(ordered_list_merge(lst1, lst2)
for lst1, lst2 in
zip(result_dict[k], v))
print(result_dict)
#Output:
{'a': ([1, 2, 3, 4, 5], [-1, -2, -3]),
'b': ([1, 2, 3], [-1, -2, -3]),
'z': ([], [-1, -3]),
'c': ([1, 2, 3], [-4])}
请注意,字典本质上是无序的(或者记住python 3.7+中的插入顺序),不应依赖于顺序。使用排序来获取元组列表,如果顺序也很重要,则使用OrderedDict。