简体   繁体   中英

Assigning a new value to a dictionary key in a in Python

I was trying to assign a new value to the key x_position in dictionary alien_0 but the method I figured causes a TypeError My Code:

alien_0={ 'x_position' : '25' , 'y_position' : '25' , 'speed' : 'medium' }
print(f"original position of alien is {alien_0['x_position']}")
if alien_0['speed'] == 'fast' :
    x_increment = 3

elif alien_0['speed'] == 'medium' :
    x_increment = 2

else:
    x_increment = 1   
#ladies and gentlemen in this case we have a slow alien

alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"our alien is at {alien_0['x_position']}")

Desired output:

original position of the alien is 25

our alien is at 27

The problem lies in line 13:

alien_0['x_position'] = alien_0['x_position'] + x_increment

You are trying to add x_increment to alien_0['x_position'] , but alien_0['x_position'] is a string, while x_increment is an integer. Python will throw a type error.

As a sidenote, you can use the += operator rather than what you are doing now, writing this instead (it's equivalent):

alien_0['x_position'] += x_increment

Anyways, to fix this problem, you can simply make alien_0['x_position'] an integer (if you wrap it with quotes, python will treat it as a string) when you define alien_0 on line 1:

alien_0={ 'x_position' : 25 , 'y_position' : 25, 'speed' : 'medium' }

Just remove the quotes around x_position , and python will treat it as an integer. I'm assuming you are doing something similar with y_position , so you might want to remove the quotation marks around that too.

Output:

original position of alien is 25
our alien is at 27

[Program finished]

Fixed code:

alien_0={ 'x_position' : 25 , 'y_position' : 25 , 'speed' : 'medium' }
print(f"original position of alien is {alien_0['x_position']}")
if alien_0['speed'] == 'fast' :
    x_increment = 3

elif alien_0['speed'] == 'medium' :
    x_increment = 2

else:
    x_increment = 1   
#ladies and gentlemen in this case we have a slow alien

alien_0['x_position'] += x_increment
print(f"our alien is at {alien_0['x_position']}")

修复代码替换alien_0['x_position'] = alien_0['x_position'] + x_incrementalien_0['x_position'] = int(alien_0['x_position']) + x_increment

字典中的数字实际上是保存为文本的,您应该删除字典中数字周围的引号 ('')。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM