I want to automatically add keys to a Python dictionary if they don't exist already. For example,
a = "a"
b = "b"
c = "c"
dict = {}
dict[a][b] = c # doesn't work because dict[a] doesn't exist
How do I automatically create keys if they don't exist?
You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.
In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value. By using the setdefault() method, you can add items with new values only for new keys without changing the values for existing keys.
We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
Use a collections.defaultdict
:
def recursively_default_dict():
return collections.defaultdict(recursively_default_dict)
my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
from collections import defaultdict
d = defaultdict(dict)
d['a']['b'] = 'c'
Also, please be careful when using dict
- it has a meaning in python: https://docs.python.org/2/library/stdtypes.html#dict
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