如何在python中加入两个具有重叠键值的词典?

时间:2017-11-24 04:39:38

标签: python python-3.x dictionary

例如,如果我的词典是,

{1:'a',2:'b',3:'c',4:'d',5:'e'}

然后我想要加入的字典,

{{1}}

5 个答案:

答案 0 :(得分:3)

看起来你根本不在乎钥匙。所以,只需弄清楚你想要加入词典的顺序:

import itertools

ordered_dicts = [dict1, dict2]  # N.B. normal dicts, not OrderedDicts!
ordered_values = [v for d in itertools.chain(ordered_dicts) for _, v in sorted(d.items())]
result = dict(zip(itertools.count(1), ordered_values))

答案 1 :(得分:2)

试试这个:

dict1 = {1:'a', 2:'b', 3:'c'}
dict2 = {1:'d', 2:'e'}

# Change the name of a key
# Note this will delete the keys 1 and 2 in dict2
dict2[4] = dict2.pop(1)    # Return the corresponding value
dict2[5] = dict2.pop(2)

# Merging the two dicts (works in Python 3.5+)
result = {**dict1, **dict2}

>>> result
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

或者,如果您想保持dict2不变:

dict1 = {1:'a', 2:'b', 3:'c'}
dict2 = {1:'d', 2:'e'}

for i, k in enumerate(dict2, start=len(dict1) + 1):    
    dict1[i] = dict2[k]


>>> dict1
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 2 :(得分:0)

dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'d',2:'e'}    
d = {}

# creating a new dictionary same as dict1 
for k,v in dict1.items():
    d[k] = v

# if dict1 needs to be updated then
# use dict1 instead of d below
for k,v in dict2.items():
    if k in d:
        d[max(d)+1] = v    # considering the max key in dict1, increment by 1
    # else:
         # any other condition

输出

# d: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 3 :(得分:0)

我们可以使用熊猫:

import pandas as pd
dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'d',2:'e'}

df1 = pd.DataFrame.from_dict(dict1, orient='index')
df2 = pd.DataFrame.from_dict(dict2, orient='index')

pd.concat([df1,df2]).set_axis(range(1,len(df1)+len(df2)+1), inplace=False).to_dict()[0]

输出:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 4 :(得分:0)

enumerate有一个start关键字参数,您可以根据需要计算任意数量。在这里,您可以使用它来解决您的问题,而无需导入任何繁重的外部模块或许多循环:

dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'d',2:'e'}



for index,values in enumerate(dict2.items(),start=len(dict1)+1):
    dict1[index] = values[1]

print(dict1)

输出:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}