Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Extract Key's Value, if Key Present in List and Dictionary
Sometimes we need to extract a value from a dictionary only if the key exists in both a list and the dictionary. Python provides the all() function combined with the in operator to check multiple conditions efficiently.
Basic Example
Here's how to extract a key's value when the key is present in both a list and dictionary ?
my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", "cool", "object", "oriented"]
my_dictionary = {"Python": 2, "fun": 4, "learn": 6}
K = "Python"
print("The key is:", K)
print("The list is:", my_list)
print("The dictionary is:", my_dictionary)
my_result = None
if all(K in container for container in [my_dictionary, my_list]):
my_result = my_dictionary[K]
print("The result is:", my_result)
The key is: Python
The list is: ['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach', 'cool', 'object', 'oriented']
The dictionary is: {'Python': 2, 'fun': 4, 'learn': 6}
The result is: 2
How It Works
The all() function returns True only if all elements in the iterable are True. In this case:
K in my_dictionarychecks if the key exists in the dictionaryK in my_listchecks if the key exists in the listall()ensures both conditions are met before extracting the value
Testing with Different Keys
Let's test with keys that exist in different combinations ?
my_list = ["Python", "is", "fun", "to", "learn"]
my_dictionary = {"Python": 2, "fun": 4, "learn": 6, "code": 8}
def extract_value(key, dictionary, items_list):
if all(key in container for container in [dictionary, items_list]):
return dictionary[key]
return None
# Test different keys
test_keys = ["Python", "fun", "code", "missing"]
for key in test_keys:
result = extract_value(key, my_dictionary, my_list)
print(f"Key '{key}': {result}")
Key 'Python': 2 Key 'fun': 4 Key 'code': None Key 'missing': None
Alternative Approaches
You can also use explicit conditions for better readability ?
my_list = ["Python", "is", "fun", "to", "learn"]
my_dictionary = {"Python": 2, "fun": 4, "learn": 6}
key = "fun"
# Method 1: Using all()
result1 = my_dictionary[key] if all(key in container for container in [my_dictionary, my_list]) else None
# Method 2: Explicit conditions
result2 = my_dictionary[key] if key in my_dictionary and key in my_list else None
print("Method 1 result:", result1)
print("Method 2 result:", result2)
Method 1 result: 4 Method 2 result: 4
Conclusion
Use all() with generator expressions to check if a key exists in multiple containers simultaneously. This approach is concise and efficient for validating conditions across different data structures before extracting values.
