试图在python中打印字典值

时间:2018-04-25 22:44:00

标签: python python-3.x dictionary

我正在尝试编写一个简单的程序,要求输入最喜欢的彩虹色首字母(ROYGBIV)并打印给定字母的值。例如,如果用户输入为“R”,程序将打印“红色”。我试图使用词典,但我无法使用它。你能帮我纠正我的错误吗?

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()`

1 个答案:

答案 0 :(得分:3)

如你所知,color目前是Python set,如下所示:

{'BlueI', 'GreenB', 'IndigoV', 'OrangeY', 'R', 'RedO', 'Violet', 'YellowG'}

构造dictionary的语法需要冒号而不是逗号,用于键/值对:

  

可以通过在大括号中放置以逗号分隔的键:值对列表来创建词典,例如:{'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}dict()构造函数。

在您的情况下,这将是:

color = {
    "R": "Red",
    "O": "Orange",
    "Y": "Yellow",
    "G": "Green",
    "B": "Blue",
    "I": "Indigo",
    "V": "Violet"
    }

或者,您可以使用词典理解:

color = {c[0]: c for c in 
         {'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'}}

最后,如果你很好奇为什么“Green”和“B”(以及其他人)被一起搞笑,那是因为Python的string literal concatenation

相关问题