2

I have two dictionary:

a=

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

and

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):

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

which is basicly a=b, how to merge A and B so the output is

{
    "2001935072": {
        "WR": "48.9",
        "nickname": "rogs30541",
        "team": 2
        "wtr": 816
    },
....
}
6
  • 1
    Possible duplicate of How to merge two dictionaries in a single expression?
    – Jongware
    Commented Feb 7, 2018 at 9:44
  • What should the rule for conflicting keys be. Meaning, which value should be taken if let's say a["2001935072"]["WR"]=48.9 and b["2001935072"]["WR"]=50? Commented Feb 7, 2018 at 9:46
  • @usr2564301 tried that method, same result Commented Feb 7, 2018 at 9:47
  • 1
    Loop the keys and merge them each, as you hold a dict of dicts, and update isn't recursive. Something like {key: a[key].update(value) for key, value in b.iteritems()}
    – casraf
    Commented Feb 7, 2018 at 9:48
  • @FlyingTeller there wont be any conflicting keys because b will only contain "wtr" and nothing else Commented Feb 7, 2018 at 9:49

3 Answers 3

3

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?)

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.
  • merge_two_dicts is just an helper function. 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

With Python 3.6+: you can do that without any helper function:

result = {k:{**a.get(k,{}),**b.get(k,{})} for k in set(a)|set(b)}
2
  • works perfectly on my machine. what is the error? I don't have access to replit. Commented Feb 7, 2018 at 10:27
  • when i run merge_two_dicts(a, b) the result is { "2001935072": { "wtr": 816 } } Commented Feb 7, 2018 at 10:30
1

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
1
  • that's very bad complexity-wise: useless O(n**2) Commented Feb 7, 2018 at 10:40
1

You can try list + dict comprehension to achieve your results:

>>> 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}}

Not the answer you're looking for? Browse other questions tagged or ask your own question.