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

时间:2013-01-25 01:09:08

标签: python dictionary python-3.x

我想知道我在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

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:6)

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

打印值:

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

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

答案 2 :(得分: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