[英]Merging dictionaries with duplicates in python
I am trying to create a code that will merge 3 difference dictionaries (two other dictionaries into the first main dictionary.) when there are duplicate keys while retaining the values. 我正在尝试创建一个代码,该代码将在保留值的同时存在重复键的情况下将3个差异词典(另外两个词典合并到第一个主词典中)。 I am currently stuck at the point where I find the duplicates and I have trouble adding them to newDict or d1. 我目前停留在找到重复项的位置,无法将它们添加到newDict或d1中。 Can anyone help me so that each duplicate becomes somekind of object where I can pass it to be added to the new dictionary containing all other keys? 谁能帮助我,使每个重复项变成某种对象,我可以将其传递给包含所有其他键的新字典吗? Thank you. 谢谢。
d1 = {'Norton': '408-771-7231', 'Edward': '415-669-7234', 'Julia':'510-669-7723'}
# Phone number information / "newDict"
d2 = {'Norton': '12345 El Monte Road', 'James': '4236 Capitol Expressway', 'Mary': '6345 Mia Circle'}
# Address information
d3 = {'Norton': 'Male', 'James': 'Male', 'John': 'Male', 'Elizabeth': 'Female'}
# Gender Information
newDict = d1
# d1 will act as the main dictionary and retain all of it's entries and receive entries.
newDictKeys=newDict.keys()
d1Keys=d1.keys()
d2Keys=d2.keys()
d3Keys=d3.keys()
allKeys = [d2Keys, d3Keys] # Left out d1Keys since it will retain it's entries.
print('Printing original dictionary entries...','\n','d1 =', d1, '\n', 'd2 =', d2, '\n', 'd3 =', d3, '\n')
print('Cross referencing keys from d1 with d2Keys and d3Keys...')
tempList = []
def addToDictForSameKey(comboDictionary, addOnDictionary, key):
return None
for keysOfDictX in allKeys:
for keyX in keysOfDictX:
print('\nChecking key:', keyX)
for keyY in newDict:
print('With this key in newDict:', keyY)
if keyX == keyY: # check for identical keys
addToDictForSameKey(newDict, d2, keyX)
print('Found Duplicate', keyX, 'with', keyY, 'in', keysOfDictX)
print('adding to newDict')
break
else:
continue
print('\n', newDict)
Output: 输出:
Printing original dictionary entries...
d1 = {'Norton': '408-771-7231', 'Edward': '415-669-7234', 'Julia': '510-669-7723'}
d2 = {'Norton': '12345 El Monte Road', 'James': '4236 Capitol Expressway', 'Mary': '6345 Mia Circle'}
d3 = {'Norton': 'Male', 'James': 'Male', 'John': 'Male', 'Elizabeth': 'Female'}
Cross referencing keys from d1 with d2Keys and d3Keys...
Checking key: Norton
With this key in newDict: Norton
Found Duplicate Norton with Norton in dict_keys(['Norton', 'James', 'Mary'])
adding to newDict
Checking key: James
With this key in newDict: Norton
With this key in newDict: Edward
With this key in newDict: Julia
Checking key: Mary
With this key in newDict: Norton
With this key in newDict: Edward
With this key in newDict: Julia
Checking key: Norton
With this key in newDict: Norton
Found Duplicate Norton with Norton in dict_keys(['Norton', 'James', 'John', 'Elizabeth'])
adding to newDict
Checking key: James
With this key in newDict: Norton
With this key in newDict: Edward
With this key in newDict: Julia
Checking key: John
With this key in newDict: Norton
With this key in newDict: Edward
With this key in newDict: Julia
Checking key: Elizabeth
With this key in newDict: Norton
With this key in newDict: Edward
With this key in newDict: Julia
{'Norton': '408-771-7231', 'Edward': '415-669-7234', 'Julia': '510-669-7723'}
Process finished with exit code 0
I want the output to look like this: 我希望输出看起来像这样:
{['Norton': '408-771-7231', '12345 El Monte Road', 'Male'] ['Edward': '415-669-7234'] ['Julia': '510-669-7723']
['James': '4325 Capitol Expressway', 'Male'] ['Mary': '6345 Mia Circle'] ['John': 'Male'] ['Elizabeth':'Female']}
Basically everything (or at least only the duplicate entries) be in a list that is inside of the dictionary in a single print statement. 基本上,所有内容(或至少只有重复的条目)都在单个print语句中的字典内的列表中。
If you are likely to have duplicates then it would probably better to make them all list
s of attributes so you don't have to do conditionals on access. 如果你很可能有重复的话,那就可能是更好的让他们所有list
属性号第因此你不必做访问条件语句。
However, if you want the conditional list on duplication then just construct the list
on duplication: 但是,如果要复制条件列表,则只需构造复制list
:
def addToDictForSameKey(comboDictionary, addOnDictionary, key):
try: # Already a list
comboDictionary[key].append(addOnDictionary[key])
except AttributeError:
comboDictionary[key] = [comboDictionary[key], addOnDictionary[key]]
for d in (d2, d3):
for k, v in d.items():
if k in d1:
addToDictForSameKey(d1, d, k):
Would create a super dict of all three dicts with duplicate keys turning into list
s of attributes. 将使用重复键将所有三个词典创建为一个超级词典,从而将其转换为属性list
。
My solution was this: 我的解决方案是这样的:
d0 = {}
for key in set(d1.keys() + d2.keys() + d3.keys()):
try:
d0.setdefault(key,[]).append(d1[key])
except KeyError:
pass
try:
d0.setdefault(key,[]).append(d2[key])
except KeyError:
pass
try:
d0.setdefault(key,[]).append(d3[key])
except KeyError:
pass
print (d0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.