VOOZH about

URL: https://www.geeksforgeeks.org/python/python-extract-keys-value-if-key-present-in-list-and-dictionary/

⇱ Extract Key's Value, if Key Present in List and Dictionary - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extract Key's Value, if Key Present in List and Dictionary - Python

Last Updated : 15 Jul, 2025

Given a list,dictionary and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. For example: a = ["Gfg", "is", "Good", "for", "Geeks"], d = {"Gfg": 5, "Best": 6} and K = "Gfg" then the output will be 5 as "Gfg" is present in both the list and the dictionary and its value is 5.

Using Set Intersection

This method converts the list to a set to take advantage of O(1) membership checks, particularly beneficial if the list is large before verifying the key in the dictionary.


Output
5

Explanation: Converting the list a into a set (a_set) enables faster membership checks and then we verify if K is present in both the set and the dictionary before retrieving the value.

Simple Conditional Check

In this method we perform straightforward membership checks using the in operator. If K is found in both the list and the dictionary then we return its corresponding value.


Output
5

Explanation: We check if K exists in both the list a and dictionary d and if both conditions are met then we return the value d[K] otherwise we return None.

Using Ternary Operator

This concise method uses a ternary operator to achieve the same result in a single line.


Output
5

Explanation: The ternary operator checks if K exists in both a and d and returns d[K] if true or None if false.

Using Dictionary's get()

Here we use the dictionary's get() method to safely retrieve the value, combined with a conditional expression to ensure that K is present in both dictionary and list.


Output
5

Explanation: get() method is used to retrieve the value for K safely and the conditional expression ensures that K must exist in both the list a and dictionary d before attempting to retrieve its value.

Comment