【问题标题】:Print just the value of a dictionary term for a specific key in Python仅打印 Python 中特定键的字典项的值
【发布时间】:2013-01-25 01:09:07
【问题描述】:

我想知道如果我有一本字典并且只想打印出特定键的值,我在 Python 中会做什么。

它将在一个变量中以及在:

dict = {'Lemonade':["1", "45", "87"], 'Coke:["23", "9", "23"] 'Water':["98", "2", "127"}
inp = input("Select key to print value for!" + "/r>>> ")
if inp in dict:
    #Here is where I would like it to print the Value list for the key that is entered.

我正在运行 Python 3.3

【问题讨论】:

  • 第一步是要有一个有效的字典对象。
  • 道歉。没有那个意图。

标签: python dictionary python-3.x


【解决方案1】:

我冒昧地重命名了您的 dict 变量,以避免隐藏内置名称。

dict_ = {
    'Lemonade': ["1", "45", "87"], 
    'Coke': ["23", "9", "23"], 
    'Water': ["98", "2", "127"],
}
inp = input("Select key to print value for!" + "/r>>> ")
if inp in dict_:
    print(dict_[inp])

【讨论】:

    【解决方案2】:

    正如 Ashwini 指出的,你的字典应该是 {'Lemonade':["1", "45", "87"], 'Coke':["23", "9", "23"], 'Water':["98", "2", "127"]}

    打印值:

    if inp in dict:
        print(dict[inp])
    

    附带说明,不要将dict 用作变量,因为它会覆盖内置类型并可能在以后导致问题。

    【讨论】:

    • 这当然只是为了举例。 dict[inp] 会在 Python 3.3 中工作吗?
    【解决方案3】:

    在 Python 3 中:

    # A simple dictionary
    x = {'X':"yes", 'Y':"no", 'Z':"ok"}
    
    # To print a specific value
    print([value for value in x.values()][1])
    

    输出:

    no
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多