I have a dictionary, which may only have these keys. But there can be 2 keys, for example 'news'
and 'coupon'
or only 'coupon'
. How to check if the dictionary is empty? (The dictionaries below are empty.)
{'news': [], 'ad': [], 'coupon': []}
{'news': [], 'coupon': []}
I wrote the code but it supposed to take only 3 keys:
if data["news"] == [] and data["ad"] == [] and data["coupon"] == []:
print('empty')
How to take not only 3 keys?
CodePudding user response:
Your dictionary is not empty, only your values are.
Test each value, using the any
function:
if not any(data.values()):
# all values are empty, or there are no keys
This is the most efficient method; any()
returns True
as soon as it encounters one value that is not empty:
>>> data = {'news': [], 'ad': [], 'coupon': []}
>>> not any(data.values())
True
>>> data["news"].append("No longer empty")
>>> not any(data.values())
False
Here, not empty means: the value has boolean truth value that is True
. It'll also work if your values are other containers (sets, dictionaries, tuples), but also with any other Python object that follows the normal truth value conventions.
There is no need to do anything different if the dictionary is empty (has no keys):
>>> not any({})
True
CodePudding user response:
If it's not empty, but all of it's values are falsy:
if data and not any(data.values()):
print(empty)