1

I need to format a dictionary with multiple integer lists as hex in python 2.7.

I've found a way to format integers from a dictionary as hex. In this example the hex will work, the hexlist will not.

dict = {
   "hex": 0x12,
   "hexlist": [0x13, 0x14]
}

print("{hex:x}, {hexlist:x}".format(**dict))

(Python Sting Formatting - Real Python)

And there is also a way to print a integer list as hex using:

''.join('{:02X}'.format(hex) for hex in hexlist)

(Format ints into string of hex)

But I can't figure out how to combine the two...

2 Answers2

2

You can always check for the variable type:

def get_hex_representation(struct):
    str = None
    if type(struct) is list:
        str = ''.join('{:02X}'.format(hex) for hex in hexlist)
    elif type(struct) is dict:
        str = '{hex:x}, {hexlist:x}'.format(**dict)
    return str

Also, you can throw an exception instead of returning None in case of your struct being neither list nor dict.

Valerii Boldakov
  • 1,751
  • 9
  • 19
0

I've solved it like this now. The idea of checking the type is the key. This function spits out a tuple with a list of the keys and values which I can further process. Probably not the most elegant solution but this works for now.

def getHexMsg(message):
    strVal = []
    strKey = []
    for key, value in message.items():
        strKey.append("{}: ".format(key))
        if type(value) is list:
            strVal.append(' '.join('{:02X}'.format(hex) for hex in value))
        elif type(value) is int:
            strVal.append('{:02X} '.format(value))
    return (strKey, strVal)