[英]Trying to print dictionary values in python
I'm trying to write a simple program that asks for input of a favorite rainbow color first letter (ROYGBIV) and print the value of the letter given. 我正在尝试编写一个简单的程序,要求输入喜欢的彩虹色首字母(ROYGBIV)并打印给定字母的值。 For example, if user input is "R", the program will print "Red". 例如,如果用户输入为“ R”,则程序将打印“红色”。 I tried to use dictionaries but I couldn't get it to work. 我尝试使用字典,但无法正常工作。 Could you help me correct my mistakes? 你能帮我纠正我的错误吗?
def rainbow():
color = {
"R", "Red"
"O", "Orange"
"Y", "Yellow"
"G", "Green"
"B", "Blue"
"I", "Indigo"
"V", "Violet"
}
userint = input("Enter first letter of fav color: ").upper()
if userint in color:
print color.get(userint,"none")
else:
print("no match")
rainbow()`
As you have it, color
is currently a Python set that looks like this: 有了它, color
当前是一个Python 集 ,如下所示:
{'BlueI', 'GreenB', 'IndigoV', 'OrangeY', 'R', 'RedO', 'Violet', 'YellowG'}
The syntax for constructing a dictionary needs colons, not commas, for key/value pairs: 对于键/值对,构造字典的语法需要冒号而不是逗号:
Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example:
{'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
, or by thedict()
constructor. 可以通过将用逗号分隔的键:值对列表放在大括号中来创建字典,例如:{'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
,或通过dict()
构造函数。
In your case, this would be: 在您的情况下,这将是:
color = {
"R": "Red",
"O": "Orange",
"Y": "Yellow",
"G": "Green",
"B": "Blue",
"I": "Indigo",
"V": "Violet"
}
Alternatively, you could use a dictionary comprehension: 另外,您可以使用字典理解:
color = {c[0]: c for c in
{'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'}}
Lastly, if you're curious as to why "Green" and "B" (among others) are smushed together, that is because of Python's string literal concatenation . 最后,如果您对“ Green”和“ B”(以及其他)为何混在一起感到好奇,那是因为Python的字符串文字串联 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.