如何合并具有相同键名的两个字典
这个问题在这里已经有了答案:
如果您想要一个不会改变原始字典并查看名称冲突的合并副本,则可能需要尝试此解决方案:
>>> dict1 = {'a': [1], 'b': [2]}
>>> dict2 = {'b': [3], 'c': [4]}
>>> import copy
>>> import itertools
>>> def merge(a, b, conflict):
new = copy.deepcopy(a)
if conflict:
for key, value in b.items():
if key in new:
counter = itertools.count(1)
# Rename 1st key.
while True:
name = '{}_{}'.format(key, next(counter))
if name not in new:
new[name] = new[key]
del new[key]
break
# Create 2nd key.
while True:
name = '{}_{}'.format(key, next(counter))
if name not in new:
new[name] = value
break
else:
new[key] = value
else:
for key, value in b.items():
new.setdefault(key, []).extend(value)
return new
>>> merge(dict1, dict2, False)
{'c': [4], 'b': [2, 3], 'a': [1]}
>>> merge(dict1, dict2, True)
{'b_2': [3], 'b_1': [2], 'c': [4], 'a': [1]}
我想你想要这个:
dict1 = {'a':[1], 'b':[2]}
dict2 = {'b':[3], 'c':[4]}
def mergeArray(conflict):
for key in dict1.keys():
if dict2.has_key(key):
if conflict==False:
dict2[key].extend(dict1[key])
else:
dict2[key+'_1'] = dict1[key]
dict2[key+'_2'] = dict2.pop(key)
else:
dict2[key] = dict1[key]
mergeArray(True);
print dict2
链接地址: http://www.djcxy.com/p/3853.html
上一篇: How to merge two dictionaries with same key names
下一篇: What's the difference between window.location and document.location in JavaScript?