Extract Key's Value, if Key Present in List and Dictionary - Python
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.
a = ["Gfg", "is", "Good", "for", "Geeks"]
d = {"Gfg": 5, "Best": 6}
K = "Gfg"
a_set = set(a) # Convert the list to a set for efficient membership testing
if K in a_set and K in d:
res = d[K]
else:
res = None
print(res)
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.
a = ["Gfg", "is", "Good", "for", "Geeks"]
d = {"Gfg": 5, "Best": 6}
K = "Gfg"
if K in a and K in d: # Check if K exists in both the list and the dictionary
print(d[K])
else:
print(None)
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.
a = ["Gfg", "is", "Good", "for", "Geeks"]
d = {"Gfg": 5, "Best": 6}
K = "Gfg"
res = d[K] if K in a and K in d else None # One-liner conditional check
print(res)
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.
a = ["Gfg", "is", "Good", "for", "Geeks"]
d = {"Gfg": 5, "Best": 6}
K = "Gfg"
res = d.get(K) if K in a and K in d else None # Retrieve value using get() if K is present in both
print(res)
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.