FXAMN FXAMN - 1 year ago 57
Python Question

Check multiple keys in a dictionary for existence and value

I would like to do something only if an object has two keys with given values:

tel = ...
nam = ...
for obj in listofobjs:
for key, val in obj.items():
if (key == 'tel' and val == tel) and \
(key == 'nam' and val == name):
# do something...

Which won't work since key and value can't be two values at the same time.

Answer Source

You don't need to loop over the .items() to do this.

for obj in listofobjs:
    if (obj.get('tel', None) == tel) and (obj.get('nam', None) == nam):

Just use .get to get the key, so that you don't get a KeyError if the key doesn't exist.

.get returns None by default, but I'm specifying it here to highlight the ability to use a different default value. If you want to use None as the default, you can leave out the second parameter from the .get call.

Replace None with a value that you know will never be a valid value for tel or nam.