简体   繁体   English

如何检查字典是否为空并且字典类似于 python 中的 {“”:“”}

[英]How to check if dictionary is empty and dictionary is like {“”:“”} in python

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我正在研究 AWS_SECRETS 并想检查是否已为此创建秘密值(KEY/VALUE 对)我正在使用 boto3 脚本,该脚本返回如下所示的空字典

{"":""}

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.目标是在{"":""}的情况下返回“空字典”,如果它像{"Key":"Value"}那么它应该返回该字典不为空。

or if anyone has a better suggestion/(s) then please suggest.或者如果有人有更好的建议/(S)那么请提出建议。

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 .注意: Terraform 用于创建AWS_SECRET ,因此AWS_SECRET将仅由 terraform 创建,但如果我需要检查它是否有一些值,我正在使用boto3处理。

You can use any(d.keys()) or any(d.values()) :您可以使用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.使用dict.keys()获取所有密钥。 You can then compare this to a tuple with just "" in it.然后,您可以将其与仅包含""的元组进行比较。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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