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

3 回答 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])
于 2013-01-25T01:11:29.160 回答
6

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

要打印值:

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

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

于 2013-01-25T01:12:11.290 回答
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
于 2018-11-15T01:35:14.990 回答