I need to loop through an array of byte arrays and then select a matching element from a dictionary. However my attempt to join the byte array fails:
roms = {
"\xff\xfe\x88\x84\x16\x03\xd1":"living_room",
"\x10\xe5x\xd5\x01\x08\x007":"bed_room"
}
devices = [bytearray(b'(\xff\xfe\x88\x84\x16\x03\xd1'), bytearray(b'\x10\xe5x\xd5\x01\x08\x007')]
for device in devices:
DEV = "".join(device)
print(roms[DEV])
>> TypeError: sequence item 0: expected str instance, int found
So it appears that you can't join an integer, is there another way?
UPDATE 1
With much help and patience from @falsetrue, I have managed to join the array. However the resulting string still throws a key error when I attempt to get the devices dictionary item:
roms = {
"\xff\xfe\x88\x84\x16\x03\xd1":"living_room",
"\x10\xe5x\xd5\x01\x08\x007":"bed_room"
}
devices = [bytearray(b'(\xff\xfe\x88\x84\x16\x03\xd1'), bytearray(b'\x10\xe5x\xd5\x01\x08\x007')]
for device in devices:
DEV = str(bytes(device)).strip('b').strip("'").strip('(') # > this results in: \xff\xfe\x88\x84\x16\x03\xd1 - but still gives keyError
#DEV = bytes(device).lstrip(b'(') # > This results in: b'\xff\xfe\x88\x84\x16\x03\xd1' - keyError
print(DEV)
print(roms["\xff\xfe\x88\x84\x16\x03\xd1"])
print(roms[DEV])
print()
>> \xff\xfe\x88\x84\x16\x03\xd1
>> living_room
>> KeyError: \xff\xfe\x88\x84\x16\x03\xd1
UPDATE 2
Here's the device info:
release='1.3.0.b1',
version='v1.8.6-379-gc44ebac on 2017-01-13',
machine='WiPy with ESP32'
Maybe someone else with a WIPY2 can verify this for me?
romsbe bytes strings? For example:b'\xff\xfe...'. If they were, anddeviceswere also byte strings, thenroms[devce]would just work.str; it will addb'...'and escape bytes; It will make situtation worse; don't do that!