How to check if dictionary is empty and dictionary is like {"":""} in python

Viewed 2077

I am working on AWS_SECRETS and want to check whether secrets values(KEY/VALUE pair) has been created or not for this i am using boto3 script which is returning an empty dictionary like below

{"":""}

Since there is no value it is being consider as a string. Please let me know how to iterate over this.

objective is to return "empty dict" in case of {"":""} and if its like {"Key":"Value"} then it should return that dictionary is not empty.

or if anyone has a better suggestion/(s) then please suggest.

Note: Terraform is being used to create AWS_SECRET, so AWS_SECRET will be created by terraform only but if I need to check whether it has some values or no that i am handing using boto3.

2 Answers

You can use any(d.keys()) or any(d.values()):

>>> d = {"": ""}
>>> any(d.keys()) or any(d.values())
False

>>> d = {"foo": ""}
>>> any(d.keys()) or any(d.values())
True

>>> d = {"foo": "bar"}
>>> any(d.keys()) or any(d.values())
True

Note that this assumes that keys and values are always strings. It would fail with other falsy values, for example:

>>> d = {False: False}
>>> any(d.keys()) or any(d.values())
False

Use dict.keys() to get all the keys. You can then compare this to a tuple with just "" in it.

if tuple(d.keys()) == ("",):
    print("dict is empty")
Related