Python : How to check if any element of a list is a key in dictionary

python-search-list-element-in-dict-key

Recently, while I was working on a Python script, I had a list of string elements and I needed to check if any element of that list was also used as a key in some dictionary. In this article, I will show you two solutions for this problem. One will simply use iteration of a for loop, while the other will use Python sets.


For our example, let's first create a list of strings and a dictionary with some random numbers as their values.
my_list=["A", "B", "C", "D"]
my_dict={"ABC":"10", "MM":"3", "A":"8"}

Here are the two solutions.

Solution 1 - iterating through the list

Here, we simply iterate through each element in the list. For each element, we check if it exists as a key in the dictionary. When the key is found, we do what we need to do and then break from the loop. If you need to find all the elements used as a dictionary key, remove the break on line 4.

for e in my_list:
    if e in my_dict:
        print("At least one element was found. Do something.")
        break

This solution is straight forward, but in my script, the list elements would rarely be found as keys in the dictionary, so the use of loops seemed wasteful to me and I wanted to try to use a solution without for loop.

Solution 2 - making use of sets

For this solution, we make use of sets. Sets are unordered collection of elements where each element is unique. In the code below, we convert both the list and the dictionary into sets using built-in set() function. Next, we use the set intersection() method to find elements that exist in both the list and as dictionary key. If there is at least one element used as a key of the dictionary, the if statement in line 3 returns true, so the if block gets executed.

my_list_set=set(my_list)
my_dict_set=set(my_dict)
if my_list_set.intersection(my_dict_set):
    print("At least one element was found. Do something.")

If you need to loop through all the elements, that are used as the dictionary key, we replace the if statement with the loop as shown here:

for i in my_list_set.intersection(my_dict_set):
    print("Element "+i+" was found. Do something.")
Note: When intersection() method doesn't find any elements that are in both sets, it returns an empty set() and not None.

Conclusion

In this article, we examined two solutions on how to Find out, if any element in the list is also used as a key in a dictionary. First, we solved this using a for loop and for 2nd solution, we used the Python sets. We also showed, how to modify the code to loop through every element that is found as a dictionary key.

Did you have to solve a similar problem and used a different solution? Let us know and we might add it here.

(Visited 38 times, 12 visits today)

Share this page

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top