Python Get Values from a Nested Dictionary

A Python nested dictionary is a dictionary with another dictionary or dictionaries nested within (dictionary of dictionaries or collection of collections). Nested dictionaries are one way to represent structured data (similar to a database table(s) relationship). An analogy for this concept is the Russian Nesting Dolls.  

Our article focuses on various ways to retrieve data from a nested dictionary.


Create a Nested Dictionary

The following code creates a dictionary containing unique ids (1000, 1001, etc.). In addition, each id has an associated nested dictionary with pertinent information relevant to that id (name, job, salary).

# raw data:
employees = {1000: {'name': 'Derek', 'job': 'support', 'salary': 89567},
             1001: {'name': 'Alice', 'job': 'coder', 'salary': 94275},
             1002: {'name': 'Lucia', 'job': 'writer', 'salary': 76500},
             1003: {'name': 'Micah', 'job': 'trainer', 'salary': 81354},
             1004: {'name': 'Sarah', 'job': 'sales', 'salary': 64152}}

Access Nested Values using Square Brackets

One way to access value(s) from a nested dictionary (employees) is to specify a key inside square brackets. If the key does not exist, a KeyError occurs, displaying the offending key name. The code below accesses and outputs the salary for employee 1002.

# raw data:
employees = {1000: {'name': 'Derek', 'job': 'support', 'salary': 89567},
             1001: {'name': 'Alice', 'job': 'coder', 'salary': 94275},
             1002: {'name': 'Lucia', 'job': 'writer', 'salary': 76500},
             1003: {'name': 'Micah', 'job': 'trainer', 'salary': 81354},
             1004: {'name': 'Sarah', 'job': 'sales', 'salary': 64152}}

result = employees[1002]['salary']
print(result)

Output

76500

Access Values using get()

Another way to access value(s) in a nested dictionary (employees) is to use the dict.get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError). The code below accesses and outputs the job for employee 1003.

# raw data:
employees = {1000: {'name': 'Derek', 'job': 'support', 'salary': 89567},
             1001: {'name': 'Alice', 'job': 'coder', 'salary': 94275},
             1002: {'name': 'Lucia', 'job': 'writer', 'salary': 76500},
             1003: {'name': 'Micah', 'job': 'trainer', 'salary': 81354},
             1004: {'name': 'Sarah', 'job': 'sales', 'salary': 64152}}

result = employees[1003].get('job')
print(result)

Output

trainer

Iterate a Nested Dictionary using the For Loop

Below is code to traverse through a nested dictionary.

for id, info in employees.items():
    print(id)
    for k in info:
        print(k, info[k])
  • Line [1] calls the for loop, references id from the top-level dictionary, info from the nested dictionary, and calls employees.items() to retrieve the appropriate data.
    • Line [2] outputs the id for each record in the top-level dictionary.
    • Line [3] loops through the nested dictionary for each id.
      • Line [4] outputs the key:value pair to the terminal.

Output – first record from Employees:

For this example, only the first record displays.

1000
name Derek
job support
salary 89567

Access Nested Values using Pandas

The Pandas library will convert the nested dictionary into a DataFrame to access the data in this section.

import pandas as pd 
df = pd.DataFrame.from_dict(employees, orient='index')

for i, j in df.iterrows():
    print(i)
    print(j)
  • Line [1] imports the library and assigns it as an object reference to pd
  • Line [2] creates a DataFrame and sets the output to df. The DataFrame has two arguments: the employees dictionary and orient. The orient=index argument forces the id to display in the far left column.
  • Line [3] starts the loop iteration. This statement repeats until there are no more rows to display (df.iterrows()).
    • Line [4] outputs the contents of the id to the terminal.
    • Line [5] outputs the values associated with that id to the terminal.

Output (Pandas DataFrame)

namejobsalary
1000Dereksupport89567
1001Alicecoder94275
1002Luciawriter76500
1003Micahtrainer81354
1004Sarahsales64152

Output (first record from Employees)

1000
name        Derek        
job         support        
salary      89567        
Name: 1000, dtype: object

Programming Humor

πŸ’‘ Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.

~~~

  • Question: Why do Java programmers wear glasses?
  • Answer: Because they cannot C# …!

Feel free to check out our blog article with more coding jokes. πŸ˜‰