user5526811
user5526811

Reputation:

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.

Upvotes: 2

Views: 652

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78546

Here's one way to do it without having to use .items():

for obj in listofobjs:
    if 'tel' in obj and 'nam' in obj and obj['tel']==tel and obj['nam']==nam:
        ...

Or you could ask for forgiveness provided all dictionary access in the if block are safe:

 for obj in listofobjs:
    try:
        if obj['tel']==tel and obj['nam']==nam:
            ...
    except KeyError:
        pass

Upvotes: 3

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

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.

Upvotes: 2

Related Questions