944,113 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 17214
  • Python RSS
Nov 10th, 2006
0

Color Dictionary

Expand Post »
I have a color data file that gives the color name and its RGB values, for instance like this:
Python Syntax (Toggle Plain Text)
  1.  
  2. red RGB(255,0,0)
  3. green RGB(0,128,0)
  4. blue RGB(0,0,255)
  5. brown RGB(165,42,42)
  6. gold RGB(255,215,0)
  7. maroon RGB(128,0,0)
I like to create a color dictionary from this file that looks like this:
Python Syntax (Toggle Plain Text)
  1.  
  2. {'red': (255,0,0), 'green': (0,128,0), 'blue': (0,0,255), ...}
How can I best do that?
Similar Threads
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Nov 11th, 2006
0

Re: Color Dictionary

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
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Nov 12th, 2006
0

Re: Color Dictionary

Jeff, thanks. I had to change the split separator from ' RGB ' to ' RGB' to make it work.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Prevent Code Errors?
Next Thread in Python Forum Timeline: Graphics User Interface for Beginners





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC