Home > database >  read json file nested dictionary
read json file nested dictionary

Time:01-30

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?

CodePudding user response:

You can use this

import json

f = open('sample.json')
data = json.load(f)
  
for i in data['items']:
    print(i)
    print(data['items'][i]['number'])
f.close()

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.

CodePudding user response:

Use could also make good use of the values() method:

for item in data["items"].values():
    print(item["number"])

If you want to get all numbers to a list, you could use list comprehension:

numbers = [item["number"] for item in data["items"].values()]
  • Related