【问题标题】:TypeError: string indices must be integers in dictionaryTypeError:字符串索引必须是字典中的整数
【发布时间】:2022-01-16 22:08:59
【问题描述】:

为什么这段代码给了我 typeError?以及如何使用变量 X 调用字典? “TypeError:字符串索引必须是整数” 我在输入中打印“浓缩咖啡”。 谢谢

machine = {"Water": 300, "Milk": 200, "Coffe": 100,}
espresso = {"Water": 50, "Milk": 0, "Coffe": 28,}


def check(x):
   
    z = machine["Water"] >= x["Water"]
    print(z)

x = input()
check(x)

【问题讨论】:

  • check 的目的是什么?请解释一下。
  • 它正在检查机器是否有足够的水输入 = espresso
  • x 的可能值是多少?
  • 不同类型的咖啡。在这种情况下,我的字典中只有 ecspresso。所以 X 可能是不同的输入“espresso”、“latte”等。
  • 我在帖子中没有看到任何“拿铁”。

标签: python dictionary typeerror


【解决方案1】:

使用字典进行映射。 this question

machine = {"Water": 300, "Milk": 200, "Coffe": 100,}
espresso = {"Water": 50, "Milk": 0, "Coffe": 28,}


def check(x):
    d ={'espresso':espresso} 
    z = machine["Water"] >= d[x]["Water"]
    print(z)

x = input()
check(x)

【讨论】:

  • 是的。能否请您再次查看我的消息。我有编辑它。我通过输入函数调用字典的问题。
【解决方案2】:

因为 x 成立: x =“浓缩咖啡” 它不是你所说的字典...... 你不能问 x["Water"]。

你需要改变: x =“浓缩咖啡” 到 x = 浓缩咖啡

【讨论】:

  • 是的。能否请您再次查看我的消息。我有编辑它。我通过输入函数调用字典的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
  • 2016-03-26
相关资源
最近更新 更多