如何知道某个值是否在嵌套字典中? [英] How to know if a value is inside a nested dictionary?

查看:58
本文介绍了如何知道某个值是否在嵌套字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我仍在学习使用方法.我有以下字典:

I'm new to Python and I'm still learning how to use. I have the follow dictionary:

dic = {'0': {'text': 'a', 'lang': 'es', 'rating': '4'}, '1': {'text': 'b', 'lang': 'es', 'rating': '3'}, '2': {'text': 'c', 'lang': 'es', 'rating': '1'}, '3': {'text': 'd', 'lang': 'es', 'rating': '2'}, '4': {'text': 'e', 'lang': 'es', 'rating': '5'}}

现在,我想知道文本(例如'a')是否是这些嵌套词典中任何一个的值(我知道有一个value()函数返回了词典的值,但是在这种情况下,它只会返回第一个字典的值,不是吗?像0,1,2,3,4)

Now, I'm trying to know if the text, for example, 'a' is a value of any of those nested dictionaries (I know there is a value() function which returns the values of the dictionaries, but in this case it will only return the values of the first dictionary, won't it? Like 0,1,2,3,4)

我尝试过

for i in range(len(dic)):
  if text in dic[i].values():
    print("Yes")
  else:
    print("No")

但是这给了我一个KeyError,值为'0'.我已经搜索了类似的问题,但是没有找到可以用来解决我的问题的问题.你能帮我么?预先感谢.

But this gives me a KeyError with value '0'. I have searched for similar questions, but haven't found any which I can use to solve my problem. Can you please help me? Thanks in advance.

推荐答案

您可以使用 any :

dic = {'0': {'text': 'a', 'lang': 'es', 'rating': '4'}, '1': {'text': 'b', 'lang': 'es', 'rating': '3'}, '2': {'text': 'c', 'lang': 'es', 'rating': '1'}, '3': {'text': 'd', 'lang': 'es', 'rating': '2'}, '4': {'text': 'e', 'lang': 'es', 'rating': '5'}}
result = any('a' in d.values() for d in dic.values())

这篇关于如何知道某个值是否在嵌套字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆