How to know if a value is inside a nested dictionary?

房东的猫 提交于 2021-01-29 06:51:22

问题


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

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)

I tried

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

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.


回答1:


You can use 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())



回答2:


You can use any with a generator comprehension, as suggested by @Ajax1234.

Or, if you do this repeatedly, you can calculate a set of values and check for membership with O(1) complexity. itertool.chain is a useful tool to combine nested values:

from itertools import chain

values = set(chain.from_iterable(i.values() for i in dic.values()))

res = 'a' in values  # True



回答3:


Starting first from what you have tried, you could indeed:

  • Use a for loop to iterate over the values of dic, that are dictionaries too.
  • Check inside each dictionary if the value of the key 'text' equals 'a'.
  • If yes, then print 'Yes' and stop the loop.
  • If the loop ends without any match, then print 'No'.

Let's do it with a beautiful for/else statement:

for d in dic.values():
    if d['text'] == 'a':
        print("Yes")
        break
else:
    print("No")


To go further, you could also:

  • use comprehension to perform the for loop and the == operation in a smarter Python way,
  • and use any to replace the if and break statements by a smarter Python built-in function.

This shorter code will in fact do exactly the same things as previous one, in a really pythonic way:

if any(d['text'] == 'a' for d in dic.values()):
    print("Yes")
else:
    print("No")

Enjoy !




回答4:


You are treating the dictionary as a list. You cannot index into a dictionary, like this:

dic[0]

But you can get the value from a given key, like so:

dic["0"] # yields {'text': 'a', 'lang': 'es', 'rating': '4'}

As such, modify your for loop as follows:

for i in dic:
    ...



回答5:


if you are sure that the string you are looking for will no be in key names, then another simple solution is converting whole dict to str and searching for string

if 'a' in str(dic):
    print("a is there")


来源:https://stackoverflow.com/questions/51104645/how-to-know-if-a-value-is-inside-a-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!