Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To merge two dictionaries of list in Python

There are two dictionaries

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}

I want another dictionary z which is a merged one of x and y such that

z = {1:['a','b','c','d','e','f'],2:['g']}

Is it possible to do this operation? I tried update operation

x.update(y)

But it gives me the following result

z= {1:['d','e','f'],2:['g']}
like image 888
athira Avatar asked Nov 26 '15 05:11

athira


3 Answers

One line solution:

{ key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }

Example 1:

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}
{ key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }

Output:

{1: ['a', 'b', 'c', 'd', 'e', 'f'], 2: ['g']}

Example 2:

one = {'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
two = {'a': [2.4, 3.4], 'c': [5.6, 7.6], 'd': [3.5, 4.5]}
{ key:one.get(key,[])+two.get(key,[]) for key in set(list(one.keys())+list(two.keys())) }

Output:

{'a': [1, 2, 2.4, 3.4], 'b': [3, 4], 'c': [5, 6, 5.6, 7.6], 'd': [3.5, 4.5]}

like image 166
Shailesh Appukuttan Avatar answered Oct 15 '22 19:10

Shailesh Appukuttan


for k, v in x.items():
if k in y.keys():
    y[k] += v
else:
    y[k] = v

Loop through dictionary getting keys and values, check if the key already exists, in which case append, else add new key with values. It won't work if your values are mixed data types that aren't lists, like you have.

   x={1:['a','b','c'], 3:['y']} 
.. y={1:['d','e','f'],2:['g']} 
..  
..  
.. for k, v in x.items(): 
..     if k in y.keys(): 
..         y[k] += v 
..     else: 
..         y[k] = v 
..      
.. print y
{1: ['d', 'e', 'f', 'a', 'b', 'c'], 2: ['g'], 3: ['y']}
like image 45
NotAnAmbiTurner Avatar answered Oct 15 '22 18:10

NotAnAmbiTurner


You could do this:

final = {}
dicts = [x,y]  # x and y are each dicts defined by op

for D in dicts:
    for key, value in D.items():  # in python 2 use D.iteritems() instead
        final[key] = final.get(key,[]).extend(value)

final.get(key,[]) will get the value in final for that key if it exists, otherwise it'll be an empty list. .extend(value) will extend that list, empty or not, with the corresponding value in D, which is x or y in this case.

like image 36
El'endia Starman Avatar answered Oct 15 '22 19:10

El'endia Starman