Home > Blockchain >  Simple way to read nested dictionary without iterating
Simple way to read nested dictionary without iterating

Time:04-24

I have a nested dictionary like this:

nest_dict = {
    "1": {
        "Name": X,
        "Class": "10",
        "Roll_no": 19289,
        "Marks": 126
    },
    "2": {
        "Name": Y,
        "Class": "12",
        "Roll_no": 19290,
        "Marks": 124
    }
}.

Please note that each sub-entry has the same set of keys, i.e. Name, Class, Roll_no, Marks. How do I get list of all_Names = [X, Y], all_Class = [10, 12], all_Roll_no = [19289, 19290], all_Marks = [126, 124] without having to iterate over the entries in the preceding level, i.e. 1,2. There should be some simple way to achieve this, right? (I am trying to parse from a json file using python3.)

CodePudding user response:

You should iterate. The code is simple enough, fast and efficient. I don't see many other ways around it.

Example:

nest_dict = {
    "1": {
        "Name": "X",
        "Class": "10",
        "Roll_no": 19289,
        "Marks": 126
    },
    "2": {
        "Name": "Y",
        "Class": "12",
        "Roll_no": 19290,
        "Marks": 124
    }
}


all_roll_numbers = set()
all_names = set()
all_classes = set()
all_marks = set()

for data in nest_dict.values():
    all_names.add(data["Name"])
    all_classes.add(data["Class"])
    all_roll_numbers.add(data["Roll_no"])
    all_marks.add(data["Marks"])

A different take:

data = {
    "Name": set(),
    "Class": set(),
    "Roll_no": set(),
    "Marks": set()
}

for item in nest_dict.values():
    for key, value in item.items():
        data[key].add(value)

CodePudding user response:

There should be some simple way to achieve this, right?

is this simple enough?:

import pandas as pd

nest_dict = {
    "1": {
        "Name": 'X',
        "Class": "10",
        "Roll_no": 19289,
        "Marks": 126
    },
    "2": {
        "Name": 'Y',
        "Class": "12",
        "Roll_no": 19290,
        "Marks": 124
    }}

res = pd.DataFrame(nest_dict.values()).T.apply(list,1).to_dict()

>>> res
'''
{'Name': ['X', 'Y'],
 'Class': ['10', '12'],
 'Roll_no': [19289, 19290],
 'Marks': [126, 124]}
  • Related