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