![]() |
VOOZH | about |
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.
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.
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.
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.
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.
This concise method uses a ternary operator to achieve the same result in a single line.
5
Explanation: The ternary operator checks if K exists in both a and d and returns d[K] if true or None if false.
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.
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.