我是Python新手,正在尝试编写一个函数来合并Python中的两个字典对象。
例如
dict1 = {'a':[1], 'b':[2]}
dict2 = {'b':[3], 'c':[4]}
我需要生成一个新的合并字典
dict3 = {'a':[1], 'b':[2,3], 'c':[4]}
函数还应该采用参数“conflict”(设置为 True 或 False)。当冲突设置为False时,上面就可以了。当冲突设置为 True 时,代码将像这样合并字典:
dict3 = {'a':[1], 'b_1':[2], 'b_2':[3], 'c':[4]}
我正在尝试附加两个字典,但不知道如何以正确的方式执行此操作。
for key in dict1.keys():
if dict2.has_key(key):
dict2[key].append(dict1[key])
如果您想要一个不会更改原始字典并监视名称冲突的合并副本,您可能需要尝试以下解决方案:
#! /usr/bin/env python3
import copy
import itertools
def main():
dict_a = dict(a=[1], b=[2])
dict_b = dict(b=[3], c=[4])
complete_merge = merge_dicts(dict_a, dict_b, True)
print(complete_merge)
resolved_merge = merge_dicts(dict_a, dict_b, False)
print(resolved_merge)
def merge_dicts(a, b, complete):
new_dict = copy.deepcopy(a)
if complete:
for key, value in b.items():
new_dict.setdefault(key, []).extend(value)
else:
for key, value in b.items():
if key in new_dict:
# rename first key
counter = itertools.count(1)
while True:
new_key = f'{key}_{next(counter)}'
if new_key not in new_dict:
new_dict[new_key] = new_dict.pop(key)
break
# create second key
while True:
new_key = f'{key}_{next(counter)}'
if new_key not in new_dict:
new_dict[new_key] = value
break
else:
new_dict[key] = value
return new_dict
if __name__ == '__main__':
main()
该程序显示两个合并字典的以下表示:
{'a': [1], 'b': [2, 3], 'c': [4]}
{'a': [1], 'b_1': [2], 'b_2': [3], 'c': [4]}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)