3
items = [{'id': 1, 'language': 'English', 'name': 'Sarah', 'description': 'Blah blah'}, {'id': 2, 'language': 'English', 'name': 'Jessica', 'description': 'More blah'}]

d = {}
for item in items:

    language = item['language']
    id = item['id']
    name = item['name']
    description = item['description']

    d[language][id] = {'name': name, 'description': description}

print(d)

I'm expecting to see in output:

{'English': {1:{'name': 'Sarah', 'description': 'Blah blah'}, 2:{'name': 'Jessica', 'description': 'More blah'}}}

But unfortunately I'm getting KeyError: Traceback: KeyError

So, the question is how to update/append value in nested dictionary? What I'm doing wrong?

Quanti Monati
  • 769
  • 1
  • 11
  • 35

2 Answers2

6

d does not contain d["English"] which you try to create with d[language][id] = {'name': name, 'description': description} - hence the error.


You cannot create intermediate dictionaries "on the fly" if they do not exist - either check if they already exist and if not create them - or use dict.setdefault(key,default) to create the entry if it does not yet exist:

items = [{'id': 1, 'language': 'English', 'name': 'Sarah', 'description': 'Blah blah'},
         {'id': 2, 'language': 'English', 'name': 'Jessica', 'description': 'More blah'}]

d = {}
for item in items:
   
    language = item['language']
    idd = item['id']
    name = item['name']
    description = item['description']

    d.setdefault(language,{})[idd] = {'name': name, 'description': description}

print(d)

Output:

{'English': {1: {'name': 'Sarah', 'description': 'Blah blah'}, 
             2: {'name': 'Jessica', 'description': 'More blah'}}}

You can use collections.defaultdict as well if you come into performance problems using setdefault - which is slightly less fast.


Related: Use cases for the 'setdefault' dict method

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
4

d is an initially empty dictionary, so does not have key language (which is 'English') yet when you try to assign a value to d[language][id].

You can change your code as follow:

for item in items:

    language = item['language']
    id = item['id']
    name = item['name']
    description = item['description']

    if not language in d:
        d[language] = {}
    d[language][id] = {'name': name, 'description': description}
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
charpank
  • 101
  • 6