Learning about Dictionaries - nesting

nesting

Sometimes, you need to store a series of dictionaries in a list or a list as a value in a dictionary, which is called nesting.

1. Dictionary list

Let's take a look at an example to create a list containing three elements:

alien_0 = {'color': 'green','points': 5}
alien_1 = {'color': 'yellow','points': 10}
alien_2 = {'color': 'red','points': 15}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)

The print result is:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

More realistically, there are more than three aliens, and each alien is automatically generated using code. In the following example, we generated 30 aliens using range():

#Create an empty list
aliens= []
#Create 30 aliens
for alien_number in range(30):
    new_alien = {'color': 'green','points': 5,'speed': 'slow'}
    aliens.append(new_alien)

#Show the first five
for alien in aliens[:5]:
    print(alien)
print("...")

#Shows how many aliens were created
print("Total number of aliens: " + str(len(aliens)))

The print result is:

{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

We can use the for loop and if statement to modify the color of some aliens. For example, to change the first three aliens to yellow, medium speed and 10 points:

#Create an empty list
aliens= []
#Create 30 aliens
for alien_number in range(0,30):
    new_alien = {'color': 'green','points': 5,'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10

#Show the first five
for alien in aliens[:5]:
    print(alien)
print("...")

The print result is:

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

2. Store list in dictionary

You need to store the list in the dictionary instead of the dictionary in the list.
For example:

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms','extran cheese'],
    }

print("You ordered a " + pizza['crust'] + "-crust pizza " +
      "with the following toppings;")
for topping in pizza['toppings']:
    print("\t" + topping)

The print result is:

You ordered a thick-crust pizza with the following toppings;
	mushrooms
	extran cheese

Whenever you need to associate a key to multiple values in the dictionary, you can nest a list in the dictionary. In the example of favorite programming languages earlier in this chapter, if everyone's answers are stored in a list, respondents can choose multiple favorite languages. In this case, when we traverse the dictionary, each respondent is associated with a language list, not a language; Therefore, in the for loop traversing the dictionary, we need to use another for loop to traverse the language list associated with the respondent:

favorite_languages = {
    'zjb': ['python','ruby'],
    'zhang': ['c'],
    'zhangji': ['ruby','go'],
    'zhangjibin': ['java','python'],
    }

for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
         print("\t" + language.title())

The print result is:

Zjb's favorite languages are:
	Python
	Ruby

Zhang's favorite languages are:
	C

Zhangji's favorite languages are:
	Ruby
	Go

Zhangjibin's favorite languages are:
	Java
	Python

Note: lists and dictionaries should not have too many nesting levels.

3. Store the dictionary in the dictionary

You can nest dictionaries in dictionaries, but when you do so, your code can quickly become complex. For example, if you have multiple website users, each with a unique user name, you can use the user name as a key in the dictionary, then store each user's information in a dictionary and use the dictionary as a value associated with the user name. In the following program, we store three items of information for each user: first name, last name and place of residence; To access this information, we traverse all user names and access the information dictionary associated with each user name:

users = {
    'aeinstein': {
        'frist': 'zhang',
        'last': 'jibin',
        'location': 'princeton',
        },
     'mcurie': {
        'frist': 'wang',
        'last': 'xiaofan',
        'location': 'paris',
        },
    }

for username,user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['frist'] + " " + user_info['last']
    location = user_info['location']
    
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

The print result is:

Username: aeinstein
	Full name: Zhang Jibin
	Location: Princeton

Username: mcurie
	Full name: Wang Xiaofan
	Location: Paris

Note: the structure of each user's dictionary is the same, making it easier to handle nested dictionaries.
If the dictionary representing each user contains different keys, the code inside the for loop will be more complex.

Tags: Python

Posted on Sun, 21 Nov 2021 23:45:01 -0500 by SergiuGothic