Color Dictionary
I have a color data file that gives the color name and its RGB values, for instance like this:
red RGB(255,0,0)
green RGB(0,128,0)
blue RGB(0,0,255)
brown RGB(165,42,42)
gold RGB(255,215,0)
maroon RGB(128,0,0)
I like to create a color dictionary from this file that looks like this:
{'red': (255,0,0), 'green': (0,128,0), 'blue': (0,0,255), ...}
How can I best do that?
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
If the data are packaged as neatly as your file shows, then I would recommend using .split() and then eval() to convert the parenthesized string to a tuple:
[php]
f = open("my_data")
colors = {}
for line in f:
line = line.strip('\n')
name, value = line.split(' RGB ')
colors[name] = eval(value) # converts string to tuple
[/php]
Jeff
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
Jeff, thanks. I had to change the split separator from ' RGB ' to ' RGB' to make it work.
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212