Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Modify a dictionary
#1
Hello everyone,

I'm new to coding and currently self-taught using online books. I am creating a dictionary with 30 aliens all the same, then modifying the first 3 to change colour/speed/point value.

The book I'm following gives the below example:

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

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

# modify the first 3 aliens
for alien in aliens[:3]:
    if alien['colour'] == 'green':
        alien['colour'] == 'yellow'
        alien['speed'] == 'medium'
        alien['points'] == 10
    elif alien['colour'] == 'yellow':
        alien['colour'] == 'red'
        alien['speed'] == 'fast'
        alien['points'] == 15

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


# show how many aliens have been created
print(f"Total number of aliens: {len(aliens)}")
The book gives an output different to the one I am receiving and I don't know why. The output I get is:

{'colour': 'green', 'points': 5, 'speed': 'slow'}
{'colour': 'green', 'points': 5, 'speed': 'slow'}
{'colour': 'green', 'points': 5, 'speed': 'slow'}
{'colour': 'green', 'points': 5, 'speed': 'slow'}
{'colour': 'green', 'points': 5, 'speed': 'slow'}
...


but the output in the book shows this:

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


Is the book incorrect? and if so, how do I adapt the code to give me the right output?
Reply
#2
on lines 12-14 and 16-18 you have == (i.e. comparison), but it should be = (assignment)
I guess it's your mistake when typing in the code from the book
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Aug-29-2019, 03:21 PM)buran Wrote: I guess it's your mistake when typing in the code from the book

Embarrassingly yes Tongue

Thank you for the help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  For Loop and Use of Brackets to Modify Dictionary in Tic-Tac-Toe Game new_coder_231013 7 2,232 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  How to modify item in dictionary? Winfried 7 3,456 Nov-21-2020, 07:12 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020