简体   繁体   English

在 Python 中为 a 中的字典键分配新值

[英]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分配一个新值,但我认为该方法会导致 TypeError 我的代码:

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外星人的原始位置是25

our alien is at 27我们的外星人 27 岁

The problem lies in line 13:问题出在第 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.您正在尝试将x_increment添加到alien_0['x_position'] ,但alien_0['x_position']是一个字符串,而x_increment是一个整数。 Python will throw a type error. Python 会抛出类型错误。

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:无论如何,为了解决这个问题,当你在第 1 行定义alien_0时,你可以简单地将alien_0['x_position']一个整数(如果你用引号将它包裹起来,python 会将其视为一个字符串):

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.只需删除x_position周围的引号,python 会将其视为整数。 I'm assuming you are doing something similar with y_position , so you might want to remove the quotation marks around that too.我假设您正在执行与y_position类似的y_position ,因此您可能也想删除它周围的引号。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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