Home > other >  nested dicts and nested lists
nested dicts and nested lists

Time:06-17

I have a nested lists and dictionary's inside a list.

confused how to access the 'Product_Name' inside nested dict

list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}]}]}]

CodePudding user response:

To retrieve the indicated value, you must provide the name of each layer and define the index (which in this case are all [0]) needed to analyze each of the containers:

list_1 = [
    {
        "group_details":[
            {
                "data":[
                    {
                        "product_details":[
                            {
                                "Product":"xyz",
                                "Invoice_No":"852",
                                "Product_Name":"abc"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Product_Name = list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"]
print(Product_Name)

Result:

abc

Additional request to find via looping:

for containers in list_1:
    for group_details in containers["group_details"]:
        for data in group_details["data"]:
            for product_details in data["product_details"]:
                print(product_details["Product_Name"])

Result:

abc

CodePudding user response:

To parse the structure, indent it:

list_1 = [
    {"group_details":[
        {"data":[
            {"product_details":[
                {"Product":"xyz", "Invoice_No":"852", "Product_Name":"abc"}]}]}]}]

print(list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"])
# abc

CodePudding user response:

list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}]}]}]}]
print(list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"])

RESULT:

abc

To do this iteratively:

for i in list_1:
    for j in i["group_details"]:
        for k in j["data"]:
            for l in k["product_details"]:
                for kk,vv in l.items():
                    if kk == "Product_Name":
                        print(vv)

CodePudding user response:

You can use the following nested for loop:

list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}] }]}]}]
for item in list_1:
    for group_details in item.get('group_details'):
        for data in group_details.get('data'):
            for product_details in data.get('product_details'):
                print(product_details.get('Product_Name'))
  • Related