skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You 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 = [str(item["number"]) for item in data["items"].values()]
    

    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.

    Login or Signup to reply.
  3. 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:

    data = {
        "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"
          }
        }
    }
    
    def process(d):
        def _process(_d, _list):
            if isinstance(_d, dict):
                if 'number' in _d:
                    _list.append(_d['number'])
                else:
                    for _v in _d.values():
                        _process(_v, _list)
            elif isinstance(_d, list):
                for _v in _d:
                    _process(_v, _list)
            return _list
        return _process(d, list())
    
    print(process(data))
    

    Output:

    ['1', '2', '3', '4', '5', '6']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search