简体   繁体   English

在python中合并2个字典

[英]Merging 2 dictionaries in python

I have two dictionary: 我有两个字典:

a= A =

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

and

b= b =

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

i've tried to merge them with both a.update(b) and a={**a, **b} but both gives this output when i print(a): 我试图将它们与a.update(b)和a = {** a,** b}合并,但在我打印(a)时都给出了此输出:

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

which is basicly a=b, how to merge A and B so the output is 基本上是a = b,如何合并A和B,所以输出是

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

I would compute the union of the keys, then rebuild the dictionary merging the inner dictionaries together with an helper method (because dict merging is possible in 3.6+ inline but not before) ( How to merge two dictionaries in a single expression? ) 我将计算键的并集,然后重建将内部字典与辅助方法合并在一起的字典(因为dict合并可以在3.6+内联中而不是之前)( 如何在单个表达式中合并两个字典?

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)

result: 结果:

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

notes: 笔记:

  • a.get(k,{}) allows to get the value for k with a default of so merge still works, only retaining values from b dict. a.get(k,{})允许使用默认值k获得k的值,因此合并仍然有效,仅保留b dict中的值。
  • merge_two_dicts is just an helper function. merge_two_dicts只是一个辅助函数。 Not to be used with a and b dicts directly or it will give the wrong result, since last merged one "wins" and overwrites the other dict values 请勿直接与ab字典一起使用,否则会给出错误的结果,因为最后合并的一个“获胜”并覆盖了其他字典值

With Python 3.6+: you can do that without any helper function: 使用Python 3.6+:您可以在没有任何辅助函数的情况下做到这一点:

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

Try this:- 尝试这个:-

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

print(a) #your updateed output

You can try list + dict comprehension to achieve your results: 您可以尝试使用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()))])

This will output: 这将输出:

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

Finally to achieve your desired output 最终达到您想要的输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM