元芳怎么了
试试这个 :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])}
猛跑小猪
您可以使用处理合并的辅助函数将此问题分为两步。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_listimport copyresult_dict = copy.deepcopy(dict1) #to ensure result_dict is an entirely new object, and mutations on result_dict do not affect dict1for 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。