Home > Mobile >  nested dictionary with values sometimes dictionary lists, sometimes a dictionary
nested dictionary with values sometimes dictionary lists, sometimes a dictionary

Time:11-28

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"

thanks you

CodePudding user response:

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.

  • Related