简体   繁体   中英

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?

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM