Python中针对特定键的字典项只打印其值

4

如果我有一个字典,并且想要打印出特定键的值,我该如何在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


4
首要步骤是拥有一个有效的字典对象。 - Ashwini Chaudhary
抱歉,没有那个意图。 - cbbcbail
3个回答

8

我已经擅自将你的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])

6
正如Ashwini所指出的那样,您的字典应该是 {'Lemonade':["1", "45", "87"], 'Coke':["23", "9", "23"], 'Water':["98", "2", "127"]}
为了打印值:
if inp in dict:
    print(dict[inp])

作为一个附加说明,不要把dict作为变量使用,因为它会覆盖内置类型并可能在以后引起问题。

当然,这只是一个例子。在Python 3.3中,dict[inp]能正常工作吗? - cbbcbail

0

在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接