Devesh Agrawal
Devesh Agrawal

Reputation: 9212

Checking for key and value in python dictionary

I need to check if key exists in Python dictionary and value of that is not null/empty for multiple keys before processing further.

exception = False

if 'key1' in d and d['key1']:
    pass
else:
    exception = True

if 'key2' in d and d['key2']:
    pass
else:
    exception = True

if 'key3' in d and d['key3']:
    pass
else:
    exception = True

if not exception:
    #Process it

I feel this code is very ugly and not Pythonic as well.

Can we write the logic better?

Upvotes: 0

Views: 81

Answers (5)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can use try/except with operator.itemgetter, or use dict.get:

from operator import itemgetter
try:
    exception = not all(itemgetter('key1', 'key2', 'key3')(d))
except KeyError:
    exception = True

Or,

exception = not all(map(d.get, ('key1', 'key2', 'key3')))

Upvotes: 2

Aaron Aben Danan
Aaron Aben Danan

Reputation: 324

This should give you the correct Bool.

exception = False
for k in ['key1', 'key2', 'key3']:
    if k in d and d[k]:
        exception = True
        break

Upvotes: 1

Thomas
Thomas

Reputation: 1245

You can use d.get(k):

if all( d.get(k) for k in ["key1","key2","key3"]):
    exception = False
else:
    exception = True

or

exception = all( d.get(k) for k in ["key1","key2","key3"])

Upvotes: 2

Maik Hasler
Maik Hasler

Reputation: 1400

The answer of @mozway is more pythonic & better, but anyways here is another approach using a function.

def check_dict(dictionary):
    for key, value in dictionary.items():
        if key not in ("key1", "key2", "key3"):
            return False
    return True

Upvotes: 0

mozway
mozway

Reputation: 262429

You can use all and a generator:

if all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
    pass
else:
    exception = True

You could actually skip using a flag:

if not all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
    # process

or

if any(k not in d or not d[k] for k in ['key1', 'key2', 'key3']):
    # process

Upvotes: 2

Related Questions