Home > Back-end >  How to extract values from a dictionary within a dictionary?
How to extract values from a dictionary within a dictionary?

Time:10-20

I have a dictionary created from a JSON using json.loads:

JSON:

data_load = '{"parts": ["part1", "part2", "part3", "part4"], "part1": {"price": 3.99, "quantity": 32}, "part2": {"price": 7.98, "quantity": 2}, "part3": {"price": 14.32, "quantity": 4}, "part4": {"price": 0.5, "quantity": 0}}'

data_dict = json.loads(data_load)

data_dict {'parts': ['part1', 'part2', 'part3', 'part4'], 'part1': {'price': 3.99, 'quantity': 32}, 'part2': {'price': 7.98, 'quantity': 2}, 'part3': {'price': 14.32, 'quantity': 4}, 'part4': {'price': 0.5, 'quantity': 0}}

I am trying to access the quantity value from a part within the nested dictionary. I am trying to do it like this:

quantities = [item['quantity'] for d_ in data_dict.values() for item in d_]

but get the error:

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    quantities = [item['quantity'] for d_ in data_dict.values() for item in d_]
  File "<pyshell#71>", line 1, in <listcomp>
    quantities = [item['quantity'] for d_ in data_dict.values() for item in d_]
TypeError: string indices must be integers

What am I doing wrong? Thanks in advance!

CodePudding user response:

This is the answer of your question:

quantities = [data_dict[p]['quantity'] for p in data_dict.get('parts')]

CodePudding user response:

Your code is currently returning a list that looks like this:

['part1', 'part2', 'part3', 'part4', 'price', 'quantity', 'price', 'quantity', 'price', 'quantity', 'price', 'quantity']

The code below extracts the quantity if the current item in the list comprehension iteration is a dictionary:

import json


data_load = '{"parts": ["part1", "part2", "part3", "part4"], "part1": {"price": 3.99, "quantity": 32}, "part2": {"price": 7.98, "quantity": 2}, "part3": {"price": 14.32, "quantity": 4}, "part4": {"price": 0.5, "quantity": 0}}'

data_dict = json.loads(data_load)

quantities = [d_["quantity"] for d_ in data_dict.values() if isinstance(d_, type({}))]

print(quantities)
  • Related