How To Know If A Value Is Inside A Nested Dictionary?
Solution 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())
Solution 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'invalues # TrueSolution 3:
Starting first from what you have tried, you could indeed:
- Use a
forloop to iterate over the values ofdic, 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")
breakelse:
print("No")
To go further, you could also:
- use comprehension to perform the
forloop and the==operation in a smarter Python way, - and use
anyto replace theifandbreakstatements 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:
ifany(d['text'] == 'a'for d in dic.values()):
print("Yes")
else:
print("No")
Enjoy !
Solution 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:
...
Solution 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'instr(dic):
print("a is there")
Post a Comment for "How To Know If A Value Is Inside A Nested Dictionary?"