Reputation: 4100
I have a dict like this:
colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}
I need to pass value of this dict to this code and it works right:
from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)
When I do below to achieve the same:
RGBColor(colour_dict["Red"])
It throws me an error as this is a string and this just want in straight number format.
I already tried converting this string to int format but nothing is working.
Overall Problem:
How to pass the value to RGBColor using dict?
Upvotes: 0
Views: 2812
Reputation: 19123
colour_dict["Red"]
is the string "0xFF, 0x00, 0x00"
, which of course can't be directly converted to an int
.
You need to convert each piece in the string and pass those values to the RGBColor
constructor:
color = RGBColor(*map(lambda v : int(v, 16), colour_dict["Red"].split(',')))
NOTE: There's a lot going on in that line, so I'll break it down and explain:
colour_dict["Red"].split(',')
extracts the color values substrings: ['0xFF', '0x00', '0x00']
map()
applies the function passed as first argument to each value in the iterable passed as second argument.
lambda v : int(v, 16)
converts v
from hex string to int
*
before map
mans "unpack the values in the iterable that follows". it's a convenient way to pass a list with the RGB values instead of calling RGBColor(R_val, G_val, B_val)
.
Since python 2 doesn't support the asterisk operator, you need to split the statement in two:
r,g,b = map(lambda v : int(v, 16), colour_dict["Red"].split(','))
color = RGBColor(r,g,b)
Upvotes: 2
Reputation: 1
colour_dict["Red"] is a string, not three numbers
you can do like this:
a = list(colour_dict["Red"])
RGBColor(int(a[0]), int(a[2]), int(a[4]))
a:['0xFF', ',', '0x00', ',', '0x00'], has 5 characters in total
Upvotes: 0
Reputation: 13195
I find the map lambda answer
a bit overkill, here is a less fancy variant:
color = RGBColor(*[int(x,16) for x in colour_dict["Red"].split(",")])
Upvotes: 0
Reputation: 125
Replace
RGBColor(colour_dict["Red"])
by
eval("RGBColor({})".format(colour_dict["Red"]))
Upvotes: 0