3

here HEX2RGB return dict value after conversion like {r:255,g:255,b:255}

    rgbValue=HEX2RGB(hex,'dict')
    r,g,b={rgbValue} # not working

so how can I assign value of each key r,g,b in the variables r,g,b like above method? or is there any other efficient way?

5
  • 3
    r,g,b = rgbValue.values() Commented Sep 5, 2021 at 15:00
  • 1
    @Epsi95: Perhaps you should place this as an answer. You should avoid answering questions in comments. Commented Sep 5, 2021 at 15:05
  • 1
    Does HEX2RGB already support producing a tuple (seems like it supports something, since 'dict' is an argument rather than a hard-coded assumption)? Commented Sep 5, 2021 at 15:11
  • 1
    @SamMatzko sure, but I want to correct one thing, we should not rely on python dict order (although 3.6+ it is ordered, but we can assume python version beforehand), so it might not be surprising that rgbValue.values() can give (b,g,r), (g,b,r) etc, I think Roman's first answer is good one. More fancy and unnecessary one can be r,g,b = map(rgbValue.__getitem__, ('r', 'g', 'b')) Commented Sep 5, 2021 at 15:21
  • @Epsi95 Ah, that makes sense. Sorry! Commented Sep 5, 2021 at 15:49

2 Answers 2

5

Use operator.itemgetter, which will not rely on any particular ordering returned by HEX2RGB;

from operator import itemgetter

dictToTuple = itemgetter('r', 'g', 'b')

r, g, b = dictToTuple(HEX2RGB(hex,'dict'))
Sign up to request clarification or add additional context in comments.

2 Comments

your solution is a little overengineerd for this specific case. It's still a very good answer. I did not know the itemgetter until now. Thanks for showing the operator module!
I would not call this overengineered. It puts a single function from the standard library to its intended use, is more efficient than three separate calls to get, and makes no assumptions about the order of the keys in the dict argument.
2

if your type is a dictionary (assumption cause you wrote {r:255,g:255,b:255})

r,g,b = rgbValue.get('r'),rgbValue.get('g'),rgbValue.get('b')

More Pythonic way:

dict = {'r':255,'g':255,'b':255}
r,g,b = dict.values()

print(r)
print(g)
print(b)

3 Comments

Most pythonic way would be to not name your dictionary dict to avoid shadowing the class
@MadPhysicist true, that's a very good comment. I had not thought of that.
Note that your second solution only works if the dict keys were created in the specific order r, g, b for versions of Python >= 3.7 where dicts are ordered, and will randomly fail for older versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.