![]() |
Modify a dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Modify a dictionary (/thread-20765.html) |
Modify a dictionary - NathanF - Aug-29-2019 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? RE: Modify a dictionary - buran - Aug-29-2019 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 RE: Modify a dictionary - NathanF - Aug-29-2019 (Aug-29-2019, 03:21 PM)buran Wrote: I guess it's your mistake when typing in the code from the book Embarrassingly yes ![]() Thank you for the help! |