Home > OS >  Can't find key in dict?
Can't find key in dict?

Time:11-18

I have a dictionary in python 3 with objects in the values, in the form of:

a={'modem0': <interfaces.modems.hw_trx_qmi.QmiModem object at 0x7fdcfe9ced70>,
   ...
   ...
  }

if I search for the key modem0 it is not being found, why might this be?

if 'modem0' in a:
    print("found")
else: 
    print("not found")

CodePudding user response:

a={'modem0': "<interfaces.modems.hw_trx_qmi.QmiModem object at 0x7fdcfe9ced70>"}
key_to_lookup = 'modem0'
if a.has_key(key_to_lookup):
   print "Key exists"
else:
   print "Key does not exist"

The value of the dictionary is not supported, whatever that format was supposed to be, so wrap it in quotes and parse it if you need it later. Also try using the has_key function like above.

CodePudding user response:

I would use get("modem0") method. Is like using a["modem0"] but returning None instead of an error if the key doesn't exist and it's value if it does.

a={'modem0': <interfaces.modems.hw_trx_qmi.QmiModem object at 0x7fdcfe9ced70>,
   ...
   ...
}
key = 'modem0'
value = a.get(key)
if value is None
    print(f'{key} not found')
print(f'{key} found')
  • Related