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']}
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]}
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']}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With