Python - Accessing Nested Dictionaries
We are given a nested dictionary and our task is to access the value inside the nested dictionaries in Python using different approaches. In this article, we will see how to access value inside the nested dictionaries in Python.
Easiest method to access Nested dictionary is by using keys. If you know the structure of nested dictionary, this method is useful.
nd = {
"fruit": {
"apple": {
"color": "red"
}}}
# Accessing the value
color = nd["fruit"]["apple"]["color"]
print(color)
Output
red
Access Nested Dictionaries Using get() Method
In this example, values in the nested market
dictionary are accessed using get()
method. The color is printed by chaining get()
calls with the respective keys for fruits and apple, providing a safe way to handle potential missing keys.
nd = {
"fruit": {
"apple": {
"color": "red"
}}}
# Safely accessing the value using get()
color = nd.get("fruit", {}).get("apple", {}).get("color")
print(color)
Output
red
Explanation:
- nested_dict.get("fruit", {}): Get the dictionary associated with key "fruit". If "fruit" is not found, it returns an empty dictionary ({}).
- .get("apple", {}): Get the dictionary for key "apple" inside the "fruit" dictionary.
- .get("color"): Get the value for key "color" inside the "apple" dictionary. Returns None if "color" does not exist.
Access Nested Dictionary - using for loop
For Loop can be used when you don't know the structure of dictionary or when keys are dynamically determined.
nd = {
"fruit": {
"apple": {
"color": "red"
}}}
# List of keys to traverse the dictionary
keys = ["fruit", "apple", "color"]
# Accessing the nested value using a loop
current = nd
for key in keys:
current = current.get(key, {})
print(current)
Output
red
Explanation:
- For loop iterates through each key in the keys list.
- current = current.get(key, {}): Get the value associated with current key. If the key is missing, it returns to an empty dictionary ({}) to prevent errors.
Access Nested Dictionaries Using Recursive Function
In this example, a recursive function named get_nd
is used to retrieve the color from the nested market
dictionary. The function recursively navigates through the dictionary hierarchy, utilizing the get()
method to handle missing keys.
def get_nd(d, keys):
if not keys:
return d
return get_nd(d.get(keys[0], {}), keys[1:])
nd = {
"fruit": {
"apple": {
"color": "red"
}}}
# List of keys to navigate
keys = ["fruit", "apple", "color"]
print(get_nd(nd, keys))
Output
red