3

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Steve
  • 945
  • 3
  • 13
  • 22
  • 3
    you need to do `d['foo']={} ` first – depperm Feb 05 '21 at 00:59
  • You're not assigning to `d['foo']`. You're assigning to `d['foo']['bar']`, which requires that `d['foo']` already exists. Just as assigning to `e['bar']` requires that `e` exists. – khelwood Feb 05 '21 at 01:00

2 Answers2

3

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
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

you need to assign d['key'] to be a dictionary first

d['a']={}
d['a']['b']= value
mutong
  • 31
  • 1