5
votes

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?

3
egidra = EGIdrA = SC2? +1 on name alone - RocketDonkey

3 Answers

27
votes

Use a collections.defaultdict:

def recursively_default_dict():
    return collections.defaultdict(recursively_default_dict)

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
4
votes
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

1
votes

For short scripts you can also use this one liner:

d = {}
d.setdefault(a, {})[b] = c