在 Python 字典中使用连字符作为键

Pal*_*era 6 python python-3.x

我必须使用 python 字典在键中使用连字符。但它不起作用任何人都可以告诉我如何解决这个问题

dict1 = dict(with_underscore = "working")
print(dict1)
dict2 = dict(with-hyphen = "Not working")
print(dict2)
Run Code Online (Sandbox Code Playgroud)

错误:

dict2 = dict(with-hyphen = "Not working")
                ^
   SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

che*_*ner 4

带连字符的键就可以了;这并不意味着所有键/值对都可以由关键字参数表示,因为它们仅限于有效标识符。您必须使用其他形式之一,例如,

dict2a = dict([("with-hyphen", "Not working")])
dict2b = {"with-hyphen": "Not working"}
dict2c = dict(**{"with-hyphen": "Not working"})
Run Code Online (Sandbox Code Playgroud)

(最后一个有点傻,但演示了可以在不显式使用关键字参数语法的情况下传递现有字典的键/值对。)