我试图根据用户定义的变量返回特定字典的预算号。我没有任何运气来解决这一点,我自己,任何帮助是非常感谢的。
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x='Rob' # x will be user defined using input()
print(team_balance[{x}]['budget'])在折叠错误中尝试上述结果:
TypeError: unhashable type: 'set'发布于 2022-05-24 15:33:48
你只需要去掉像这样的花括号:
print(team_balance[x]['budget'])如果添加它们,则结果是一个集合,您可以这样检查:
isinstance({x}, set)集合不能用作字典键,因为它是不可操作的(这意味着它可以更改)。
发布于 2022-05-24 16:01:56
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x=input() # user will enter this value使用“试除”处理异常
try:
print(team_balance[x.capitalize()]['budget'])
except:
print("Entered value not in owners list ")发布于 2022-05-24 15:54:25
问题来自最后一行的“{}”。
定义字典时,使用字符串作为键。因此,在从字典中调用值时,必须使用字符串。
x='Rob'也在x中分配一个字符串,所以它是好的。我们可以使用函数type来检查对象的类:
>>> type(x)
<class 'str'>最后一行的问题是将字符串转换为一组字符串的{x}。一个集合就像一个列表,但却是无序的,不可改变的,而且只有一个值。
>>> type({x})
<class 'set'>因此,由于您没有使用相同类型的对象来获取比用来设置值的对象,所以它无法工作。
你得到的错误信息
TypeError:无法理解的类型:“set”
因为set对象是不可协商的,所以它不能用作字典键(解释了为什么是这里)。但是,即使集合是一个可理解的对象,您也不会有您想要的值,因为它不等于您用来定义键的值。
只需删除{}:
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x='Rob' # x will be user defined using input()
print(team_balance[x]['budget'])
>>> 200https://stackoverflow.com/questions/72365550
复制相似问题