Merging dictionary value lists in python -


i'm trying merge 3 dictionaries, have same keys, , either lists of values, or single values.

one={'a': [1, 2], 'c': [5, 6], 'b': [3, 4]} two={'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5]} three={'a': 1.2, 'c': 3.4, 'b': 2.3} 

what need items in values added 1 list.

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

i have tried several things, put values nested lists. e.g.

out=dict((k, [one[k], two.get(k), three.get(k)]) k in one) {'a': [[1, 2], [2.4, 3.4], 1.2], 'c': [[5, 6], [5.6, 7.6], 3.4], 'b': [[3, 4], [3.5, 4.5], 2.3]} 

i tried updating looping through values:

out.update((k, [x x in v]) k,v in out.iteritems()) 

but results same. have tried add lists, because third dictionary has float, couldn't it.

check=dict((k, [one[k]+two[k]+three[k]]) k in one) 

so tried first add lists in values of 1 , two, , append value of three. adding lists worked well, when tried append float third dictionary, whole value went 'none'

check=dict((k, [one[k]+two[k]]) k in one) {'a': [[1, 2, 2.4, 3.4]], 'c': [[5, 6, 5.6, 7.6]], 'b': [[3, 4, 3.5, 4.5]]} new=dict((k, v.append(three[k])) k,v in check.items()) {'a': none, 'c': none, 'b': none} 

as one-liner, dictionary comprehension:

new = {key: value + two[key] + [three[key]] key, value in one.iteritems()} 

this creates new lists, concatenating list one corresponding list two, putting single value in three temporary list make concatenating easier.

or for loop updating one in-place:

for key, value in one.iteritems():     value.extend(two[key])     value.append(three[key]) 

this uses list.extend() update original list in-place list two, , list.append() add single value three.

where went wrong:

  • your first attempt creates new list values one, two , three nested within rather concatenating existing lists. attempt clean copied nested lists across.

  • your second attempt didn't work because value in three not list not concatenated. created new list 1 value.

  • your last attempt should not have used list.append() in generator expression, because store return value of method, none (its change stored in v directly , list doesn't need returning again).

demo of first approach:

>>> one={'a': [1, 2], 'c': [5, 6], 'b': [3, 4]} >>> two={'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5]} >>> three={'a': 1.2, 'c': 3.4, 'b': 2.3} >>> {key: value + two[key] + [three[key]] key, value in one.iteritems()} {'a': [1, 2, 2.4, 3.4, 1.2], 'c': [5, 6, 5.6, 7.6, 3.4], 'b': [3, 4, 3.5, 4.5, 2.3]} 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -