【问题标题】:Calling a Key in a dictionary using a variable?使用变量调用字典中的键?
【发布时间】:2022-06-11 21:28:07
【问题描述】:

我试图能够根据用户定义的变量返回特定字典的预算编号。我没有任何运气自己解决这个问题,非常感谢任何帮助。

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'

【问题讨论】:

  • 你想达到什么目的?我可以看到两个错误,我无法说出您的真正意思。您的意思是打印:team_balance['ROB']['budget']?或者:team_balance[x.capitalize()]['budget']?
  • @quamrana Rob 是临时的,正如他们在评论中所说的那样。 # x will be user defined using input().
  • team_balance[x]['budget']。由于您不需要 { },您会收到错误消息。在我看来,您可能会将其与f-strings 混淆。这也可以:team_balance[f"{x}"]['budget'],但它会是一种不必要的复杂方式来做一些非常简单的事情。
  • print(team_balance[x.capitalize()]['budget']) 尽管注意用户输入并考虑如果给定名称 ( x) 不在字典中
  • @LancelotduLac:是的,这是 OP 解释他们想要实现的目标之后的下一步。

标签: python list dictionary variables


【解决方案1】:
owners = ['rob','andre']
team_balance = {}

for name in owners:
    team_balance[name.capitalize()] ={'budget':200}

x=input() # user will enter this value

使用try except处理异常

try:
  print(team_balance[x.capitalize()]['budget']) 
except:
  print("Entered value not in owners list ")

【讨论】:

    【解决方案2】:

    你只需要像这样省略花括号:

    print(team_balance[x]['budget'])
    

    如果你添加它们,结果是一个集合,你可以这样检查:

    isinstance({x}, set)
    

    集合不能用作字典键,因为它是不可散列的(这几乎意味着它可以更改)。

    【讨论】:

      【解决方案3】:

      问题来自最后一行的“{}”。

      定义字典时,您使用字符串作为键。所以当你从字典中调用一个值时,你必须使用字符串。

      x='Rob' 也在x 中分配了一个字符串,这样就可以了。 我们可以使用函数type来检查对象的类:

      >>> type(x)
      <class 'str'>
      

      最后一行的问题是 {x} 将您的字符串转换为一组字符串。集合就像一个列表,但无序、不可更改且只有唯一值。

      >>> type({x})
      <class 'set'>
      

      因此,由于您使用的对象类型与用于设置值的对象类型不同,因此无法正常工作。

      你得到的错误信息

      TypeError: unhashable type: 'set'

      是因为一个set对象是unhasable,所以它不能用作字典键(解释了为什么here)。但即使一个集合是一个可散列的对象,你也不会有你想要的值,因为它不等于你用来定义键的值。

      只需删除 {}

      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'])
      
      
      >>> 200
      

      【讨论】:

        猜你喜欢
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2011-08-16
        • 2023-03-19
        相关资源
        最近更新 更多