-1

I am trying to dynamically define variables from a dictionary in python. I need my variables to be strings, they should appear something like this: lightgreen = "#2ecc71". To do this I added HEX_VALUE = "'" + HEX_VALUE + "'" however adding this I encountered an error

> 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

As seen from above, this adds ':' to the first part of the variable, so my question is: how can I prevent this?

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))
Chris
  • 351
  • 2
  • 4
  • 13

1 Answers1

4

As some mentioned in the comments, there is no reason to use exec to make python define new variables. The hex values are already strings in the dictionary so you can just access them directly like so:

lightgreen = COLOURS["lightgreen"]

Although I'll not there is no reason to define variables with the same name as the key of the dict since the dict can just always be accessed directly when necessary.

Alex
  • 1,172
  • 11
  • 31