Nesting
List of dictionaries:
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] forAlieninchAliens:Print(alien)
We first created three dictionaries, each of which represents an alien. At the place, we put these dictionaries
To a list named aliens. Finally, we iterate through the list and print out each of the aliens:
{'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 to store aliensAliens = []#Create 30 Green Aliens? forAlien_numberinchRange (30):? New_alien= {'Color':'Green','points': 5,' Speed':'Slow'}? Aliens.append (New_alien)#show the top five aliens? forAlieninchAliens[:5]:Print(Alien)Print("...")#show how many aliens have been created?Print("Total number of aliens:"+ STR (len (aliens)))
{' 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 ', ' color ': ' green ', ' Points ': 5}
...
Total number of aliens:30
These aliens all have the same characteristics, but in Python's view, each alien is independent, which allows us to
Site to modify each alien.
Under what circumstances do we need to deal with hordes of aliens? Imagine that as the game progresses, some aliens
Will change color and move faster. If necessary, we can use the FOR loop and if statements to modify some alien colors.
For example, to change the first three aliens to yellow with a medium speed and a value of 10 points, you can do this:
# Create an empty list for storing aliens aliens = []# Create 30 Green aliens for 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 top five aliens
For alien in Aliens[0:5]:
Print (alien)
Print ("...")
Since we want to modify the first three aliens, we need to traverse a slice that contains only these aliens. Currently, all aliens
are green, but that's not always the case, so we've written an if statement to make sure that only green aliens are modified. If
The alien is green, we will change its color to ' yellow ', change its speed to ' medium ', and change its points to 10,
As shown in the following output:
{' Speed':'Medium','Color':'Yellow','points': 10}{' Speed':'Medium','Color':'Yellow','points': 10}{' Speed':'Medium','Color':'Yellow','points': 10}{' Speed':'Slow','Color':'Green','points': 5}{' Speed':'Slow','Color':'Green','points': 5}
You can further extend this loop by adding a elif code block that changes the yellow aliens to move faster and
The red aliens with a value of 15 dots are shown below (only the loops are listed here, not the entire program):
forAlieninchAliens[0:3]:ifalien['Color'] =='Green': alien['Color'] ='Yellow'alien[' Speed'] ='Medium'alien['points'] = 10elifalien['Color'] =='Yellow': alien['Color'] ='Red'alien[' Speed'] ='Fast'alien['points'] = 15
To store a list in a dictionary:
In the following example, two aspects of pizza are stored: the skin type and the list of ingredients. The list of ingredients is a
The value associated with the key ' toppings '. To access the list, we use the dictionary name and the key ' toppings ', just like accessing the dictionary
The same as the other values. This returns a list of ingredients instead of a single value:
#store information about the points of Pisa? Pizza = {'Crust':'Thick','Toppings': ['Mushrooms','Extra Cheese'],}#overview of the points of the pizza?Print("You ordered a"+ pizza['Crust'] +"-crust Pizza"+"With the following toppings:")? forToppinginchpizza['Toppings']:Print("\ t"+ topping)
You ordered a thick-crust pizza with the following toppings:
Mushrooms
Extra cheese
You can nest a list in a dictionary whenever you need to associate a key to multiple values in the dictionary.
Note that the nesting levels of lists and dictionaries should not be too many. If the nesting level is much more than the previous example, it is likely to be simpler
Solution to the problem.
To store a dictionary in a dictionary:
Users = {'Aeinstein': {' First':'Albert',' Last':'Einstein',' Location':'Princeton',},'Mcurie': {' First':'Marie',' Last':'Curie',' Location':'Paris',},}? forUsername, User_infoinchusers.items ():?Print("\nusername:"+username)? Full_name= user_info[' First'] +" "+ user_info[' Last']location= user_info[' Location']? Print("\tfull Name:"+full_name.title ())Print("\tlocation:"+Location.title ()) Username:aeinsteinfull Name:albert Einsteinlocation:princeton
Username:mcuriefull Name:marie Curielocation:paris
Note that the structure of each user's dictionary is the same, although Python does not have such a requirement, but this makes the embedded
Set of dictionaries is easier to handle. If you indicate that each user's dictionary contains a different key, the code inside the For loop will
More complex.
Python Learning 5-nesting