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.
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.
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.
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.
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'}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With