Dennis Grasso
Dennis Grasso

Reputation: 123

Create a new dictionary combining two dictionaries with equal keys without changing source dictionary

I have these two dicts:

a = {'blocked': [29.686],
 'dns': [-1],
 'connect': [-1],
 'send': [0.09],
 'wait': [36.912],
 'receive': [0.24],
 'ssl': [-1],
 '_queued': [4.029]}
 
b = {'blocked': [0],
 'dns': [0],
 'connect': [28.219],
 'send': [0.126],
 'wait': [33.053],
 'receive': [0.279],
 'ssl': [28.219],
 '_queued': [1.312]}

And I want to obtain that result (extend value for each key):

c = {'blocked': [29.686, 0], 
'dns': [-1, 0], 
'connect': [-1, 28.219], 
'send': [0.09, 0.126], 
'wait': [36.912, 33.053], 
'receive': [0.24, 0.279], 
'ssl': [-1, 28.219], 
'_queued': [4.029, 1.312]}

So I wrote this:

c = {k: v.append(*b[k]) for k, v in a.items()}

or also:

c = {k: v.extend(b[k]) for k, v in a.items()}

But append and extend return None and dict c is filled with those None. The dict a is also changed to what c was intended as a result.

c -> {'blocked': None, 'dns': None, 'connect': None, 'send': None, 'wait': None, 'receive': None, 'ssl': None, '_queued': None}

I know I can copy a to c and then do the operation without assigning the dictionary to anything getting c modified

c = a # trick
{k: v.extend(b[k]) for k, v in c.items()}

Is there a clean way to do this without using a "passing" dictionary to not change a?

Upvotes: 0

Views: 30

Answers (1)

Nick
Nick

Reputation: 147216

You want list concatenation:

c = { k : v + b[k] for k, v in a.items() }

Output:

{
 'blocked': [29.686, 0],
 'dns': [-1, 0],
 'connect': [-1, 28.219],
 'send': [0.09, 0.126],
 'wait': [36.912, 33.053],
 'receive': [0.24, 0.279],
 'ssl': [-1, 28.219],
 '_queued': [4.029, 1.312]
}

If it's possible that there are keys in a that do not exist in b, use b.get with a default empty list rather than b[k]:

c = { k : v + b.get(k, []) for k, v in a.items() }

Upvotes: 1

Related Questions