The following fills out a dictionary describing a hypothetical person, by assigning to new keys over time:
rec = {} rec['name'] = 'Bob' rec['age'] = 40.5 rec['job'] = 'developer/manager' print( print(rec['name']) )
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:
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'] )
The following dictionary is nested:
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:
We can access the components of this structure:
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 )