Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nested dictionary with values sometimes dictionary lists, sometimes a dictionary

I would like to extract the keys and value into a nested dictionary with list comprehension,
one of the dictionary keys sometimes has the value a dictionary and sometimes a list of dictionaries

Data={"main": {"sub_main": [   
    
    {"id": "995", "item": "850", "price": {"ref": "razorback", "value": "250"}},
    
    {"id": "953", "item": "763", "price": [{"ref": "razorback", "value": "250"},{"ref": "sumatra", "value": "170"},{"ref": "ligea", "value": "320"} ]}, 
    
    ]}}

I tried with this list comprehension:

result = [item["price"] for item in Data["main"]["sub_main"]]

how to output only certain values from the "price" key according to a filter on the "id" key , for example, output only the values of the "price" key for the "id" key which has the value "953"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks you

>Solution :

You can use ‘if’ statement in your list comprehension to extract data specific to an id.

result = [item["price"] for item in Data["main"]["sub_main"] if item["id"]=="953"]

Output

[[{'ref': 'razorback', 'value': '250'}, {'ref': 'sumatra', 'value': '170'}, {'ref': 'ligea', 'value': '320'}]]

result variable will only inlcude the filtered data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading