只打印Python中特定键的字典术语的值

2024-06-16 09:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如果我有一个字典,我想打印出一个特定键的值,我在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


Tags: thetokeyforinput字典isvalue
3条回答

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

要打印值:

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

另外,不要使用dict作为变量,因为它将重写内置类型,并且可能在以后引起问题。

我冒昧地重命名了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])

在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

相关问题 更多 >