Skip to content
Advertisement

Extracting key and value from tuple of dictionaries (taken from json file) in python

I have a JSON file which is a tuple of multiple dictionaries and I want to extract keys and values from some of them.

The file looks something like this (this is just an example of the structure with random keys and values):

JavaScript

What I want to extract all names (Ana, Bob, Chloe) and their ids something like this:

Ana = 1234,
Bob = 5678

etc.

Whatever that I have already tried gives back attribute errors etc. I am not even sure how to iterate through this correctly so that it takes name and ID because they don’t have the same location (the name is inside element dict).

I even tried converting the file to list.

Advertisement

Answer

Firstly, you must open this JSON file and let the json library parse this file, resulting in a loaded dictionary. See Reading JSON from a file? for more information. Once you have your dictionary, which I’ll call users, you can perform this dictionary comprehension:

JavaScript

which outputs:

JavaScript

Note that this can cause issues if there are people with overlapping names! For example:

JavaScript

Outputs:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement