Update all matching keys in list of dictionaries with value in Python

Question:

key = 'take'
val = 5

dicts = [
    OrderedDict([
        (u'rt', 0), 
        (u'janoameezy', 0), 
        (u'calum', 0), 
        (u'is', 0), 
        (u'me', 0), 
        (u'whenever', 0), 
        (u'i', 0), 
        (u'take', 0), 
        (u'a', 0), 
        (u'selfie', 0), 
        (u'http', 0), 
        (u't', 0), 
        (u'co', 0), 
        (u'sxn68vta2a', 0)
    ]), 
    OrderedDict([
        (u'relax', 0), 
        (u'and', 0), 
        (u'take', 0), 
        (u'notes', 0), 
        (u'while', 0), 
        (u'i', 0), 
        (u'tokes', 0), 
        (u'of', 0), 
        (u'the', 0), 
        (u'marijuana', 0), 
        (u'smoke', 0)
    ])
]

How can I replace all instances of key with val?

Asked By: Fo.

||

Answers:

You just loop through the list:

for od in dicts:
    if key in od:
        od[key] = val

The key in od tests for membership first; the key will only be updated if it was present before.

Answered By: Martijn Pieters

Since Python 3.3 you can use collections.ChainMap and subclass it to update all its maps

>>> from collections import ChainMap

>>> class DeepChainMap(ChainMap):
...     def __setitem__(self, key, value):
...         for mapping in self.maps:
...             if key in mapping:
...                 mapping[key] = value
...         self.maps[0][key] = value

>>> dcm = DeepChainMap(*dicts)
>>> dcm[key] = val  # key = 'take'; val = 5
>>> dicts

dicts = [
    OrderedDict([
        ...
        (u'take', 5),
        ...
    ]),
    OrderedDict([
        ...
        (u'take', 5),
        ...
    ])
]

Answered By: wolfrevo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.