Search code examples
pythondictionarymutable

How to change one item in dictionary


I need a function to change one item in composite dictionary. I've tried something like..

def SetItem(keys, value):

    item = self.dict

    for key in keys:          
        item = item[key]

    item = value

and

 SetItem(['key1', 'key2'], 86)

It should be equivalent to self.dict['key1']['key2'] = 86, but this function has no effect.


Solution

  • Almost. You actually want to do something like:

    def set_keys(d, keys, value):
        item = d
        for key in keys[:-1]:
            item = item[key]
        item[keys[-1]] = value
    

    Or recursively like this:

    def set_key(d, keys, value):
        if len(keys) == 1:
            d[keys[0]] = value
        else:
            set_key(d[keys[0]], keys[1:], value)
    

    Marcin's right though. You would really want to incorporate something more rigorous, with some error handling for missing keys/missing dicts.