I'm having trouble trying to get a list of values from a specific key inside an json array using python. Using the JSON example below, I am trying to create a list which consists only the values of the name
key.
Original JSON:
[
{
"id": 1,
"name": "Bulbasaur",
"type": [
"grass",
"poison"
]
},
{
"id": 2,
"name": "Ivysaur",
"type": [
"grass",
"poison"
]
}
]
Expected:
["Bulbasaur", "Ivysaur"]
Below is the code of my approach:
import json
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
print(contents[:]["name"])
I'm trying to go to an approach where i don't need to loop every single index and append them, something like the code above. Is this approach possible using python' json library?
Try this with list comprehensions:
This is not a real answer to the question. The real answer is to use a list comprehension. However, you can make a class that allows you to use specifically the syntax you tried in the question. The general idea is to subclass
list
so that a slice like[:]
returns a special view (another class) into the list. This special view will then allow retrieval and assignment from all the dictionaries simultaneously.Your original code would now work out of the box with just one additional wrap in
UniformDictList
:You cannot do
contents[:]["name"]
sincecontents
is a list is a dictionary with integer indexes, and you cannot access an element from it using a stringname
.To fix that, you would want to iterate over the list and get the value for key
name
for eachitem
The output will be