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.). Each id has an associated nested dictionary with pertinent information relevant to that id (name, job, salary).

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 and, the offending key name is displayed. The code below accesses and outputs the salary for employee 1002.

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.

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.

  • 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.

For this example, only the first record displays.

for id, info in employees.items():
    print(id)
    for k in info:
        print(k, info[k])

Output – first record from Employees:

1000
name Derek
job support
salary 89567

Access Nested Values using Pandas

In this section, the pandas library will convert the nested dictionary into a DataFrame to access the data.

  • 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 argumentforces 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()). The variable i outputs the contents of the id. The variable j outputs the values associated with that id.
import pandas as pd 
df = pd.DataFrame.from_dict(employees, orient='index')

for i, j in df.iterrows():
    print(i)
    print(j)

Panda DataFrame:

      name      job         salary
1000  Derek     support     89567
1001  Alice     coder       94275
1002  Lucia     writer      76500
1003  Micah     trainer     81354
1004  Sarah     sales       64152

Output – first record from Employees:

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