consider this example
{
"items": {
"PYGXGE": {
"id": "a",
"number": "1"
},
"sbe7oa": {
"id": "b",
"number": "2"
},
"sbe7ob": {
"id": "c",
"number": "3"
},
"sbe7oc": {
"id": "d",
"number": "4"
},
"sbe7od": {
"id": "e",
"number": "5"
},
"sbe7oe": {
"id": "f",
"number": "6"
}
}
}
i want to access all nested number values, how can I do that in python here is my code so far:
import json
f = open('sample.json')
data = json.load(f)
for i in data['items']:
print(i)
f.close()
also, is this format for json better or list of dict?
3
Answers
You can use this
It depends on how you want to store the data and what data structure suits your need. If you want to store your data separately and planning to make that accessible through other files over the network, JSON file is my way to go.
You could also make good use of the
values()
method:If you want to get all numbers to a list, you could use list comprehension:
If you need to access individual items frequently, then the dictionary format is more efficient, because you can access values by their keys O(1) time. Ultimately, the choice between a dictionary and a list of dictionaries should be based on your specific needs of your use case.
A recursive analysis of the Python dictionary facilitates identifying values at any level – i.e., not limited to the structure shown in the question.
All that’s required are the values associated with a key ‘number’ that might be found in any dictionary.
Therefore:
Output: