Home > Programming > Not so easy: updating a Python dictionary

Not so easy: updating a Python dictionary

January 23rd, 2009 Leave a comment Go to comments


Here's a problem that looks very easy but that it took me more time than I thought to solve.

Consider the following function prototype:

def updateDictValue(dictionary, keyPath, newValue)

dictionary is a normal Python dict, keyPath is a string referring to a key inside dictionary and newValue is the new value which should be put at the key correspondent to keyPath.

An example:

dictionary = {"a": {"b": {"c": {"d": 3}}}}
keypath = "a.b.c.d"
newValue = 4

Now write the body of the function so that at the end of the execution dictionary is

{"a": {"b": {"c": {"d": 4}}}}


My not so pretty solution is here:

def updateDictValue(dictionary, keyPath, newValue):
    tokens = keyPath.split(".")
    if len(tokens) > 1:
        prev = dictionary[tokens[0]]
        for token in tokens[1:]:
            if token == tokens[-1]:
                prev[token] = newValue
            else:
                 prev = prev.get(token)
        return dictionary
    else:
        dictionary[keyPath] = newValue
        return dictionary
 


At the beginning I simply thought using eval but you can't assign a value inside the eval expression so that won't work, and even if you could, how do you specify the correct type ? You're limited to the types offered by the string formatting options in Python (%s, %d etc...).

Now that I've posted here I'm sure I'm going to implement it faster next time but I'm curios about other ways of solving this problem. Any ideas ?

Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.