Python:合并两个字典

问题描述

这是我当前的代码

Set-ExecutionPolicy -ExecutionPolicy Unrestricted

这是我目前得到的结果:

A = {1 : "one",2 : "two"}
B = {2 : "dva",3 : "three"}
d = {}

for key in set(list(A.keys()) + list(B.keys())):
    try:
        d.setdefault(key,[]).append(A[key])
    except KeyError:
        pass

    try:
        d.setdefault(key,[]).append(B[key])
    except KeyError:
        pass
print(d)

我需要做什么才能得到如下所示的结果?

{1: ['one'],2: ['two','dva'],3: ['three']}

解决方法

您可以首先使用 dict 运算符创建一个新的 **

new_dict = {**A,**B}
>>> new_dict
{1: 'one',2: 'dva',3: 'three'}

然后在 for 键的交集上循环 set

>>> for dupe_key in set(A) & set(B):
...     new_dict[dupe_key] = [A[dupe_key],B[dupe_key]]
...
>>> new_dict
{1: 'one',2: ['two','dva'],3: 'three'}
,

此代码实现了您的需求:

A = {1 : "one",2 : "two"}
B = {2 : "dva",3 : "three"}

d = A.copy()
for key,val in B.items():
    if key in d:
        if isinstance(d[key],list):
            d[key].append(val)
        else:
            d[key] = [d[key],val]
    else:
        d[key] = val

print(d)

但是,正如评论中提到的,它的通用性较差,这意味着您必须每次都检查值的类型(更多的 if-else 检查)才能使用它。

,

这是一个快速的解决方案:

A = {1 : "one",3 : "three"}
d = {**A}

for k,v in B.items():
    d[k] = [d[k],v] if k in d else v

print(d)

输出:

{1: 'one',3: 'three'}

这是一个更通用的解决方案,适用于无限数量的字典:

def cool_dict_merge(dicts_list):
    d = {**dicts_list[0]}
    for entry in dicts_list[1:]:
        for k,v in entry.items():
            d[k] = ([d[k],v] if k in d and type(d[k]) != list
                    else [*d[k],v] if k in d
                    else v)
    return d

测试:

>>> A = {1: "one",2: "two"}
>>> B = {2: "dva",3: "three"}
>>> C = {2: "chewbacca",3: "ThReE",4: "four"}
>>> D = {0: "zero",4: "jack",5: "five"}
>>> cool_dict_merge([A,B,C,D])
{1: 'one','dva','chewbacca'],3: ['three','ThReE'],4: ['four','jack'],0: 'zero',5: 'five'}

请注意,正如其他人指出的那样,在大多数情况下,您当前获得的结果可能更可取,因为它更具通用性且更易于使用。不过,我们不知道您的用例,因此请使用您觉得最舒服的方法。

,

我使用字典和 groupby 组来查找类似的数据集。 Pandas 非常适合将数据转换为字典、元组或列表。

A = {1 : "one",3 : "three"}

z1=zip(A.keys(),A.values())
z2=zip(B.keys(),B.values())

mylist=[]
mylist.append(list(z1))
mylist.append(list(z2))

variables=[]
phrases=[]
for item in mylist:
   for k,v in item:
       variables.append(k)
       phrases.append(v)
df=pd.DataFrame(zip(variables,phrases),columns=['variable','phrase'])

grpDictionary=df.groupby('variable').groups

resultDictionary={}
for key,values in grpDictionary.items():
    resultDictionary[key]=" ".join(df.iloc[values]['phrase'])

print(resultDictionary)

输出:

{1: 'one',2: 'two dva',3: 'three'}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...