Home > Enterprise >  Checking for key and value in python dictionary
Checking for key and value in python dictionary

Time:11-24

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?

CodePudding user response:

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

CodePudding user response:

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"])

CodePudding user response:

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')))

CodePudding user response:

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

CodePudding user response:

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
  • Related