Python - Dictionary Dictionary Nesting

Introduction

The following fills out a dictionary describing a hypothetical person, by assigning to new keys over time:

Demo

rec = {} 
rec['name'] = 'Bob' 
rec['age']  = 40.5 
rec['job']  = 'developer/manager' 

print( print(rec['name']) )

Result

The following code uses a dictionary to capture object properties, but it codes it all at once and nests a list and a dictionary to represent structured property values:

Demo

rec = {'name': 'Bob', 
       'jobs': ['developer', 'manager'], 
       'web':  'www.book2s.com', 
       'home': {'state': 'good', 'zip': 12345}} 

print( rec['name'] )
print( rec['jobs'] )
print( rec['jobs'][1] )
print( rec['home']['zip'] )

Result

The following dictionary is nested:

Demo

rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 
       'jobs': ['dev', 'mgr'], 
       'age':  40.5}

Here, we have a three-key dictionary at the top (keys "name," "jobs," and "age").

The values are:

  • a nested dictionary for the name to support multiple parts, and
  • a nested list for the jobs to support multiple roles.

We can access the components of this structure:

Demo

rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 
       'jobs': ['dev', 'mgr'], 
       'age':  40.5} 
           # ww w.  ja  v  a2 s  .c  o m
print( rec['name'] )                         # 'name' is a nested dictionary 
print( rec['name']['last'] )                 # Index the nested dictionary 
print( rec['jobs'] )                        # 'jobs' is a nested list 
print( rec['jobs'][-1] )                     # Index the nested list 
rec['jobs'].append('janitor')       # Expand Bob's job description in place 
print( rec )

Result