在python中将字典与重复项合并

时间:2017-02-05 03:29:12

标签: python dictionary

我正在尝试创建一个代码,当有重复的键同时保留值时,将3个不同的词典(其他两个词典合并到第一个主词典中)。 我目前卡在我找到重复项的位置,我无法将它们添加到newDict或d1。任何人都可以帮助我,以便每个副本成为某种对象,我可以将其传递给包含所有其他键的新词典吗?谢谢。

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)

输出:

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

我希望输出看起来像这样:

   {['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']}

基本上所有(或至少只有重复的条目)都在一个打印语句中的字典内的列表中。

2 个答案:

答案 0 :(得分:0)

如果您可能有重复项,那么最好将它们设置为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):

list

将创建所有三个dicts的超级dict,并且重复键变为sed -e 's/\([^\[]*\"[A-Z\-]*\)\",\"\(.*\)/\1,\2/' 属性。

答案 1 :(得分:0)

我的解决方案是:

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)