Home > Enterprise >  Python multiple nested dictionaries
Python multiple nested dictionaries

Time:08-25

I'm trying to loop through a nested dictionary in python and retrieve specific information to display in the front end.

The dictionary looks similar to this:

dict = {
  "fruits": {
    "banana": {
       "code": "fgr",
       "price": "4€"
    },
    "apple": {
        "code": "fgf",
        "price": "1€"
    }
  },
  "vegetables": {
    "spinach": {
       "code": "hgg",
       "price": "2€"
    },
    "carrot": {
        "code": "hgl",
        "price": "3€"
    }
}

I would like to loop through this dictionary and extract the dict name (fruits or vegetables), the item name (apple, banana, ..) and the value of the most inner key

I would like to display it like that in my frontend (or output it on my console first this way):

Fruits:
  Banana:
    3€
  Apple:
    1€
Vegetables:
  Spinach:
    2€
  Carrot: 
    3€ 

I've tried to loop through the map like this:

for key, value in dict.items():
  print(key)

  for i in value:
    print(i   ':', value[i])

But unfortunately this will print the keys as well as the values, instead of only the values of the most inner dict.

CodePudding user response:

You'll have a better time understanding what you're doing if you name your variables a bit better (not to mention it's generally not a good idea to shadow the built-in name dict):

categories = {
  "fruits": {
    "banana": {
       "code": "fgr",
       "price": "4€"
    },
    "apple": {
        "code": "fgf",
        "price": "1€"
    }
  },
  "vegetables": {
    "spinach": {
       "code": "hgg",
       "price": "2€"
    },
    "carrot": {
        "code": "hgl",
        "price": "3€"
    }
  },
}

for category, category_products in categories.items():
    print(category)
    for product_name, info in category_products.items():
        print(f"\t{product_name} - {info['price']}")

prints out

fruits
    banana - 4€
    apple - 1€
vegetables
    spinach - 2€
    carrot - 3€

CodePudding user response:

for key, value in dict.items():
    print(f"{key.title()}:")
    for k, v in value.items():
        print(f"\t{k.title()}:")
        print(f"\t\t{v['price']}")

Output:

Fruits:
    Banana:
        4€
    Apple:
        1€
Vegetables:
    Spinach:
        2€
    Carrot:
        3€
  • Related