[Tutor] merging dictionary values based on key
ski
norman at khine.net
Thu Mar 12 21:24:37 CET 2009
Hello,
I have this issue, which I am unsure on how to solve.
>>> mylist1 = {'a': 'x123', 'b':'12'}
>>> mylist2 = {'a': 'x234', 'c': 'a23'}
>>> for k in mylist2:
... if k in mylist1:
... mylist1[k] = [mylist1[k], mylist2[k]]
... else:
... mylist1[k] = mylist2[k]
...
>>> mylist1
{'a': ['x123', 'x234'], 'c': 'a23', 'b': '12'}
>>>
this merges the two dictionaries, but what should be the method if:
>>> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c':
'a23'}, {'a': 'x234', 'c': 'XX123'} .... ]
where mylist has nth number of dictionaries and i want to merge the
values of the keys that are the same?
Thanks
Norman
More information about the Tutor
mailing list