check if element is in a list in a dictionary value - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: check if element is in a list in a dictionary value (/thread-37197.html) |
check if element is in a list in a dictionary value - ambrozote - May-11-2022 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 RE: check if element is in a list in a dictionary value - ndc85430 - May-11-2022 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. RE: check if element is in a list in a dictionary value - ambrozote - May-11-2022 (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") RE: check if element is in a list in a dictionary value - Coricoco_fr - May-11-2022 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") RE: check if element is in a list in a dictionary value - deanhystad - May-11-2022 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)
|