Skip to content Skip to sidebar Skip to footer

Python Update Dictionary Based On Key Value Pair

this question is how to check two dictionary list and for same keys and update main dictionary with key value pair from other dictionary. First dictionary main = [ {'country': u'CY

Solution 1:

Another one may be -

import itertools
main = [
{'country': u'CYPRUS', 'naziv': 'AKEL', 'FCI': 2}, 
{'country': u'CYPRUS', 'naziv': 'DIKO', 'FCI': 4}, 
]
second = [
{'likes': '8625.00', 'talks': '1215.00', 'naziv': 'AKEL'}, 
{'likes': '2746.00', 'talks': 0, 'naziv': 'DIKO'}, 
]


lst = sorted(itertools.chain(main,second), key=lambda x:x['naziv'])
list_c = []
for k,v in itertools.groupby(lst, key=lambda x:x['naziv']):
    d = {}
    for dct in v:
        d.update(dct)
    list_c.append(d)
print list_c

"Shemeless copy of mgilson"

Solution 2:

Why don't you just update the main dictionary list with same key values from second dictionary, simply this way:

>>> for i,d inenumerate(second):
    main[i].update(second[i])


>>> main
[{'likes': '8625.00', 'FCI': 2, 'talks': '1215.00', 'country': u'CYPRUS', 'naziv': 'AKEL'}, {'likes': '2746.00', 'FCI': 4, 'talks': 0, 'country': u'CYPRUS', 'naziv': 'DIKO'}]

Post a Comment for "Python Update Dictionary Based On Key Value Pair"