Variable returns empty even when assigned by dictionary – Python

Question:

When crying to convert an RGB value to Hex using dictionaries one variable returns correctly as the Key turned to the Hex value but when tried with a second variable it returns as None. capitalization doesnt seem to be the problem.

def rgb(r, g, b):
    Rgb_to_Hex = {
        "0": "0",
        "1": "1",
        "2": "2",
        "3": "3",
        "4": "4",
        "5": "5",
        "6": "6",
        "7": "7",
        "8": "8",
        "9": "9",
        "10": "A",
        "11": "B",
        "12": "C",
        "13": "D",
        "14": "E",
        "15": "F"
    }
    one = str(int(r / 16))
    two = str(((r / 16) - int(r/16)) * 16)
    print(two) #two is equal to 14 when r is 254
    #three
    #four
    #five
    #six
    one1 = str(Rgb_to_Hex.get(one))
    two2 = str(Rgb_to_Hex.get(two))
    print(one1) # Console: F (works)
    print(two2) # Console: None (doesnt work)
    return one1 + two2

Tried to change the data type but it didnt seem to function either

Asked By: Sanderdrack

||

Answers:

The issue is that r / 16 gives a float value, so the final result has ".0" at the end when converted to a string, which doesn’t match any of the dict keys. Instead, use r % 16 to get the remainder.

Note that it is far simpler to use a f-string to format the int in hexadecimal.

hexR = f'{r:X}'
Answered By: Unmitigated
  • For integer division, prefer a // b, rather than int(a / b);
  • For remainder, prefer a % b, rather than a - b * (a // b);
  • For division and remainder, you can use divmod which combines // and %;
  • The keys of a dictionary don’t have to be string, you can use int directly.
def rgb_to_hex(r, g, b):
    hexit = '0123456789ABCDEF' # = string.digits + string.ascii_uppercase[:6]
    qr, rr = divmod(r, 16)
    qg, rg = divmod(g, 16)
    qb, rb = divmod(b, 16)
    return ''.join(hexit[h] for h in (qr,rr,qg,rg,qb,rb))

print(rgb_to_hex(254, 100, 57))
'FE6439'
Answered By: Stef
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.