Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a value deep in a dict dynamically

Tags:

python

If I have a nested dict d = {'a':{'b':{}}} and a string 'a.b.c' and a value 'X'

I need to put the value in the dict based on the key string.

What I want to achieve can be hard coded as d['a']['b']['c'] = 'X' but I need to do it dynamically. The keystring could be of any length.

For bonus points: I also need to create keys if they don't exist like 'a.b.z' but I'm sure I can figure that out if I can work out the case where they already exist.

like image 691
Jake Avatar asked Jan 23 '14 01:01

Jake


People also ask

How do you change a value in a nested dictionary?

Adding or updating nested dictionary items is easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one. If the key is new, it is added to the dictionary with its value.

Can you modify dict in Python?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.

Can a dictionary have a string as value?

Dictionary values can be just about anything (int, lists, functions, strings, etc). For example, the dictionary below, genderDict has ints as keys and strings as values.


1 Answers

def set(d, key, value):
    dd = d
    keys = key.split('.')
    latest = keys.pop()
    for k in keys:
        dd = dd.setdefault(k, {})
    dd.setdefault(latest, value)

d = {}
set(d, 'a.b.c', 'X')
set(d, 'a.b.d', 'Y')
print(d)

Result:

{'a': {'b': {'c': 'X', 'd': 'Y'}}}
like image 123
gawel Avatar answered Sep 24 '22 10:09

gawel