Search code examples
pythonpython-3.xdictionarykey

Why am I gettng a KeyError when adding a key to a dictonary?


I am still trying to learn the ins and outs of Python dictionaries. When I run this:

#!/usr/bin/env python3
d = {}
d['foo']['bar'] = 1

I get KeyError: 'foo'. But in How can I add new keys to a dictionary? it says that "you create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten." So why am I getting the key error?


Solution

  • You have, at least, two options:

    1. Create nested dictionaries in order:
    d = {}
    d['foo'] = {}
    d['foo']['bar'] = 1
    
    1. Use collections.defaultdict, passing the default factory as dict:
    from collections import defaultdict
    
    d = defaultdict(dict)
    d['foo']['bar'] = 1