我试图在python中从字典动态定义变量。我需要将变量作为字符串,它们应该显示为:lightgreen = "#2ecc71".
为此,我添加了HEX_VALUE = "'" + HEX_VALUE + "'"
但是添加了这个我遇到了错误
> Traceback (most recent call last):
line 22, in <module>
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))
File "<string>", line 1
darkblue:='#2980b9'
^
SyntaxError: invalid syntax
如上所示,这会在变量的第一部分添加':',所以我的问题是:如何防止这种情况?
COLOURS = {
"lightgreen":"'#2ecc71'",
"darkgreen":"#27ae60",
"lightblue":"#3498db",
"darkblue:":"#2980b9",
"lightpurple":"#e74c3c",
"darkpurple":"#8e44ad",
"lightred":"#e74c3c",
"darkred":"#c0392b",
"lightorange":"#e67e22",
"darkorange":"#d35400",
"lightyellow":"#f1c40f",
"darkyellow":"#f39c12",
"lightteal": "#1abc9c",
"darkteal": "#16a085",
"lightnavy": "#34495e",
"darknavy": "#2c3e50"
}
for COLOUR_NAME, HEX_VALUE in COLOURS.items():
HEX_VALUE = "'" + HEX_VALUE + "'"
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))
答案 0 :(得分:4)
正如评论中提到的那样,没有理由使用exec
来使python定义新变量。十六进制值已经是字典中的字符串,因此您可以直接访问它们,如下所示:
lightgreen = COLOURS["lightgreen"]
虽然我没有理由定义与dict键同名的变量,因为dict可以在必要时直接访问。