PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to update value of key in nested dictionary?

 July 21, 2022     append, dictionary, python, python-3.x     No comments   

Issue

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?


Solution

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



Answered By - Patrick Artner
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing