Home > Net >  Assignment of dictionary in for-loop
Assignment of dictionary in for-loop

Time:11-04

I want to create a list of 30 aliens. They have different characteristics, and a dictionary contains these characteristics.

aliens = []

for num in range(30):
    alien_new = {"color": "green", "points": "5", "speed": "low"}
    aliens.append(alien_new)

for alien in aliens[:10]:
    if alien["color"] == "green":
        alien = {"color": "yellow", "points": "10", "speed": "medium"}
for alien in aliens[:5]:
    if alien["color"] == "yellow":
        alien = {"color": "red", "points": "15", "speed": "fast"}
aliens = []

for num in range(30):
    alien_new = {"color": "green", "points": "5", "speed": "low"}
    aliens.append(alien_new)

for alien in aliens[:10]:
    if alien["color"] == "green":
        alien["color"] = "yellow"
        alien["points"] = "10"
        alien["speed"] = "medium"
for alien in aliens[:5]:
    if alien["color"] == "yellow":
        alien["color"] = "red"
        alien["points"] = "15"
        alien["speed"] = "fast"

I don't know why there are two differnt answers.

CodePudding user response:

aliens is a list of 30 dictionnaries.

Inside the for loop (for alien in aliens[:10]:), alien is a variable that 'points' to one of those dictionnaries.

When you execute alien["color"] = "yellow", you change one of the fields of this dictionnary.

Whereas when you execute alien = {"color": "yellow", "points": "10", "speed": "medium"}, you make alien variable point to a new dictionnary that contains yellow color, but you do not change aliens array or its content.
You only change the value of the local loop variable.

  • Related