仅打印 Python 中特定键的字典术语的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14513740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print just the value of a dictionary term for a specific key in Python
提问by cbbcbail
I am wondering what I do in Python if I have a dictionary and I want to print out just the value for a specific key.
我想知道如果我有字典并且只想打印出特定键的值,我会在 Python 中做什么。
It will be in a variable as well as in:
它将在一个变量中以及在:
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.
I am running Python 3.3
我正在运行 Python 3.3
回答by wim
I have taken the liberty of renaming your dictvariable, to avoid shadowing the built-in name.
我冒昧地重命名您的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])
回答by Volatility
As Ashwini pointed out, your dictionary should be {'Lemonade':["1", "45", "87"], 'Coke':["23", "9", "23"], 'Water':["98", "2", "127"]}
正如阿什维尼指出的那样,你的字典应该是 {'Lemonade':["1", "45", "87"], 'Coke':["23", "9", "23"], 'Water':["98", "2", "127"]}
To print the value:
打印值:
if inp in dict:
print(dict[inp])
As a side note, don't use dictas a variable as it will override the built in type and could cause problems later on.
作为旁注,不要dict用作变量,因为它会覆盖内置类型并可能在以后导致问题。
回答by Fouad Boukredine
In Python 3:
在 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])
Output:
输出:
no

