在python中合并2个字典

时间:2018-02-07 09:43:39

标签: python dictionary

我有两本字典:

α=

{
    "2001935072": {
        "WR": "48.9",
        "nickname": "rogs30541",
        "team": 2
    },
....
}

B =

{
    "2001935072": {
        "wtr": 816
    },
....
}

我试图将它们与a.update(b)和a = {** a,** b}合并,但是当我打印(a)时两者都给出了这个输出:

{
    "2001935072": {
        "wtr": 816
    },
....
}

基本上是a = b,如何合并A和B所以输出是

{
    "2001935072": {
        "WR": "48.9",
        "nickname": "rogs30541",
        "team": 2
        "wtr": 816
    },
....
}

3 个答案:

答案 0 :(得分:3)

我会计算键的并集,然后重建将内部词典与辅助方法合并的字典(因为dict合并可能在3.6+内联但不是之前)(How to merge two dictionaries in a single expression?

a={
    "2001935072": {
        "WR": "48.9",
        "nickname": "rogs30541",
        "team": 2
    }
    }
b= {
    "2001935072": {
        "wtr": 816
    },

}
def merge_two_dicts(x, y):
    """Given two dicts, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

result = {k:merge_two_dicts(a.get(k,{}),b.get(k,{})) for k in set(a)|set(b)}

print(result)

结果:

{'2001935072': {'WR': '48.9', 'nickname': 'rogs30541', 'team': 2, 'wtr': 816}}

注释:

  • a.get(k,{})允许使用默认值获取k的值,因此合并仍然有效,仅保留b dict中的值。
  • merge_two_dicts只是一个帮助函数。不要直接与ab dicts一起使用,否则会产生错误的结果,因为最后合并了一个"胜利"并覆盖其他字典值

使用Python 3.6+:你可以在没有任何帮助函数的情况下做到这一点:

result = {k:{**a.get(k,{}),**b.get(k,{})} for k in set(a)|set(b)}

答案 1 :(得分:1)

试试这个: -

for i,j in a.items():
    for x,y in b.items():
        if i==x:
            j.update(y)

print(a) #your updateed output

答案 2 :(得分:1)

你可以尝试list + dict理解来实现你的结果:

>>> a = {"2001935072":{"WR":"48.9","nickname":"rogs30541","team":2}}
>>> b = {"2001935072":{"wtr":816}}
>>> l = dict([(k,a.get(k),b.get(k)) for k in set(list(a.keys()) + list(b.keys()))])

这将输出:

>>> [('2001935072', {'WR': '48.9', 'nickname': 'rogs30541', 'team': 2}, {'wtr': 816})]

最后实现您想要的输出

>>> dict((k,{**va,**vb}) for k,va,vb in l)
>>> {'2001935072': {'WR': '48.9', 'nickname': 'rogs30541', 'team': 2, 'wtr': 816}}