python - Adding dictionaries -


i'm trying build function

def adding_3dict(d1,d2,d3) 

the function gets 3 dictionaries d1,d2,d3, create them 1 dictionary d such if key found in more 1 dictionary d1,d2,d3, value in d tuple values in dictionaries. rest of pairs d1,d2,d3, copied d . function returns new dictionary d.

example:

d1={1:'a',3:'d',5:'e'} d2={1:'b',3:(11,22),7:'f',4:'q'} d3={2:'c',3:'x',4:'t',8:'g'} 

the output dictionary is:

d =  {1: ('a', 'b'), 2: 'c', 3: ('d', (11, 22), 'x'), 4: ('q', 't'), 5: 'e', 7: 'f', 8: 'g'} 

i tried:

import collections  d1={} d2={} d3={} def adding_3dict(d1,d2,d3):     d={}     d=dict(d1.items() + d2.items()+ d3.items() )      return d 

i tried , output is:

>>>  >>> adding_3dict( {1:'a',3:'d',5:'e'}, {1:'b',3:(11,22),7:'f',4:'q'} , {2:'c',3:'x',4:'t',8:'g'} ) {1: 'b', 2: 'c', 3: 'x', 4: 't', 5: 'e', 7: 'f', 8: 'g'} #the output >>>  

how can change output

{1: 'b', 2: 'c', 3: 'x', 4: 't', 5: 'e', 7: 'f', 8: 'g'} 

to

{1: ('a', 'b'), 2: 'c', 3: ('d', (11, 22), 'x'), 4: ('q', 't'), 5: 'e', 7: 'f', 8: 'g'} 

here's solution accept arbitrary number of dictionaries:

from itertools import chain  def custom_dictmerge(*args):     result = {}     keys = set(chain(*(d.keys() d in args)))     k in keys:         result[k] = tuple(d[k] d in args if k in d)         if len(result[k]) == 1:             result[k] = result[k][0]     return result 

call custom_dictmerge(d1, d2, d3).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -