how can I check if an element is in a list in a dictionary value? for instance
how can I get this code to output "Found it"
a = "Doors"
dict = {"a":["Doors","Windows"],"b":"Stairs"}
if a in dict.values():
print("Found it")
else:
print("sorry")
Thank you
Well, remember that the value you're getting that contains what you're looking for is a list, so you need to look inside that. Can you have nested containers containing the value? Recursion would help in that case.
(May-11-2022, 04:07 PM)ndc85430 Wrote: [ -> ]Well, remember that the value you're getting that contains what you're looking for is a list, so you need to look inside that. Can you have nested containers containing the value? Recursion would help in that case.
something like this?
a = "Doors"
dict = {"a":["Doors","Windows"],"b":"Stairs"}
for val in dict.values():
if a in val:
print("Found it")
else:
print("sorry")
Hello,
(May-11-2022, 04:18 PM)ambrozote Wrote: [ -> ]something like this?
You can use for/else loop:
a = "Doors"
dict = {"a":["Doors","Windows"],"b":"Stairs"}
for val in dict.values():
if a in val:
print("Found it")
break
else:
print("sorry")
Another possible approach is:
a = "Doors"
dict = {"a":["Doors","Windows"],"b":"Stairs"}
if any(val for val in dict.values() if a in val):
print("Found it")
else:
print("sorry")
import itertools
x = {
2:[2, 4, 6, 8],
3:[3, 6, 9, 12],
5:[5, 10, 15, 20]
}
values = set(itertools.chain(*x.values())) # Get set containing all values from dictionary
for i in range(10):
print(i, i in values)
Output:
0 False
1 False
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True