cbb*_*ail 4 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.
Run Code Online (Sandbox Code Playgroud)
我正在运行Python 3.3
我冒昧地重命名你的dict变量,以避免影响内置名称.我也假设你在python3上,如果你在2.x上,你应该改变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])
Run Code Online (Sandbox Code Playgroud)
正如Ashwini指出的,你的词典应该是 {'Lemonade':["1", "45", "87"], 'Coke':["23", "9", "23"], 'Water':["98", "2", "127"]}
要打印值:
if inp in dict:
print(dict[inp])
Run Code Online (Sandbox Code Playgroud)
作为旁注,请不要将其dict用作变量,因为它将覆盖内置类型,并可能在以后导致问题.