[note] nesting of python: dictionary list, store list in dictionary, store dictionary in dictionary

1, Nesting of python

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. We can nest dictionaries in lists, lists in dictionaries, and even dictionaries in dictionaries.

2, Dictionary list

Remember our previous example of aliens, if dictionary alien_0 contains all kinds of information about an alien, so how should we manage when there are many aliens? One way is to create a list of aliens, where each alien is a dictionary containing all kinds of information about the alien.
Example: create a list containing three aliens and traverse the list.

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)

Output result:

A more realistic scenario is that there are more than three aliens. And every alien is automatically generated using code.
Example: using range() to generate 30 aliens.

#Create an empty list for storing aliens
aliens=[]

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

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

#Shows how many aliens were created
print(f"Total numbers of aliens:{len(aliens)}")

Output result:

As the game progresses, some aliens will change color and move faster. If necessary, you can use the for loop and if statement to modify the color of some aliens.
Example: to change the first three aliens to yellow, the speed is medium and the value is 10 points.

#Create an empty list for storing aliens
aliens=[]

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

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

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

Output result:

3, Store list in dictionary

Sometimes you need to store a list in a dictionary instead of a dictionary in a list.
For example, in the example of our previous pizza shop, when we were learning the list, the list can only store the pizza ingredients to be added; Now if we use a dictionary, we can include not only a list of ingredients, but also other descriptions of pizza.

Example: in the following code, two aspects of pizza information can be stored: skin type and ingredient list. The ingredient list is a value associated with the key 'toppings'. To access the list, we use the dictionary name and the key 'toppings', just as we access other values in the dictionary. This will return a list of ingredients instead of a single value:

#Store information about the pizza you ordered
pizza={
    'crust':'thick',
    'toppings':['mushroom','extra cheese'],
}

#Overview of pizza ordered
print(f"You order a {pizza['crust']}-crust pizza" 
      "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

Output result:

When you need to associate a key with multiple values in the dictionary, you can nest a list in the dictionary. Let's do another example

Example: investigate people's favorite programming languages. If the respondents have multiple favorite languages, they need to put the answers in the list. Next, we create such a nested list (nested list in the dictionary)

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}

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

Output result:

5, Store dictionary in dictionary

Nesting dictionaries in dictionaries can start to complicate the code. 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 the value associated with the user name.

Example: the following program stores 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 dictionary associated with each user name.

users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
    },

    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    },

}

for username,user_info in users.items():
    print(f"\nUsername:{username}")
    full_name=f"{user_info['first']} {user_info['last']}"
    location=user_info['location']

    print(f"\tFull name:{full_name.title()}")
    print(f"\tLocation :{location.title()}")

Output result:

Keywords: Python Back-end

Added by leony on Tue, 22 Feb 2022 12:55:02 +0200