Search code examples
pythondictionarynestedkey-value

What is the proper way to extract the value from nested dictionary in Python?


A nested dictionary:

nested_dict = {"fruit": {"apple":{"status": "new", "sold": True},
                         "banana": 10,
                         "watermelon": 30},
               "meat": {"red": 39, "white": 13}}

res = nested_dict.get("fruit", {}).get("apple", {}).get("status")
if res:
    print(f"{res = }")

Is there any better practise to extract the value from the nested dictionary?


Solution

  • I'm not totally sure about speed, but personally I like to reference dictionary elements in the same way you would access the elements of a list, tuple, or most other python data structure, like this for your example:

    In [24]: res = nested_dict["fruit"]["apple"]["status"]
    
    In [25]: print(res)
    new
    

    I should also note it looks like you're constructing something known as a JSON file, a common file format which Python has a nice module for, i.e the json module. Might be worth looking into!