【问题标题】:How do i obtain the value of an item in a conditional statement?如何在条件语句中获取项目的值?
【发布时间】:2021-09-04 12:49:52
【问题描述】:

例如,如何在条件语句中获取字典项的值

names = {"one":"john", "two":"justin"}
prompt = input("enter option: ")
if prompt == names["one"]:
    print("hey, I am here")

你会建议我用类似于第 3 行的解决方案来解决这个问题,这样如果用户输入一个键,例如“one”,它就会打印“john”

【问题讨论】:

  • 我对问题进行了编辑,使其易于理解。我想要实现的是使用密钥来带出第 3 行中的值
  • @JUSTINKPAKPA,有两个答案应该可以解决您的问题。
  • @JUSTINKPAKPA,如果它有效,你必须接受一个回答,这样其他人就会明白你已经解决了你的问题。
  • 如所写,您的代码正在检查用户是否键入了 john john,而不是一个。你想print(names.get(prompt))吗?

标签: python-3.x dictionary if-statement


【解决方案1】:

在


在 Python 中存在一个名为 in 的关键字,它有多种使用方式。
例如:

>>> 'i' in "in"
True

.keys() 和 .values()


dict内置类有两个方法:keys()和values()。
它们是这样使用的:

>>> Dictionary = {"one":"john", "two":"justin"}
>>> Dictionary.keys()
["one", "two"]
>>> Dictionary.values()
["john", "justin"]

它们也是可下标的,因为它们返回列表。

回答


你可以这样做:

names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
    print("Hey, I'm here")

编辑


这应该可行:

# According to PEP-8 you should always leave a space after ':' in a dict
names = {"one": "john", "two": "justin"}
prompt = input("enter number: ")
if prompt in names.keys():
        print(f"Hey, {names[prompt]} is here!")

【讨论】:

  • @JUSTINKPAKPA,有没有出现任何错误?
  • 那么出了什么问题?你写了“john”作为输入,但什么也没发生?
  • 哦,我明白了,等一分钟,你就会得到答案
  • 好的@JUSTINKPAKPA,检查我的编辑,这应该可以。
【解决方案2】:

你可以试试in

names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
    print("hey, I am here")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多