python dictionary error when getting value from a given key -
i'm starting coding in python since yesterday , i'm going without problems. context program read rfid card , use readed tag associated username. work in embedded linux (debian gnu/linux 7 (wheezy)) on terra board. python version (python 2.7.3).
i create dictionary fill key/value pairs (both strings). when try value using 1 key exception don't understand.
def findtagbynumber(self, key): global tags value = "" try: print("all dictionary: " + str(self.tags)) print("get name key: " + str(key)) value = self.tags[key] print("found name key: " + str(value)) except exception ex: print("exception: " + str(ex)) return value
the result this:
root@ariag25:/home/python# python main.py rfid::initialize rfid::get tag configurations rfid::serial port opened dictionary: {'4d0055ab3a': 'test1', '4d0055b6e4j': 'test2'} name key: 4d0055b6e4j exception: '\x024d0055b6e4j\x03' rfid::couldn't found tag
can explain wrong code?
you still including rfid start , end flags; bytes hex values 02 , 03; these un-printable bytes not visible when print them directly. none of keys in dictionary include these bytes.
just printing key means don't see bytes, are there:
>>> key = '\x024d0055b6e4j\x03' >>> print key 4d0055b6e4j >>> key '\x024d0055b6e4j\x03' >>> print repr(key) '\x024d0055b6e4j\x03'
the repr()
function helps make bytes visual.
you strip bytes:
key.strip('\x02\x03')
demo:
>>> key = '\x024d0055b6e4j\x03' >>> key.strip('\x02\x03') '4d0055b6e4j' >>> tags = {'4d0055ab3a': 'test1', '4d0055b6e4j': 'test2'} >>> key in tags false >>> key.strip('\x02\x03') in tags true
another option add bytes dictionary keys instead:
{'\x024d0055ab3a\x03': 'test1', '\x024d0055b6e4j\x03': 'test2'}
Comments
Post a Comment