In Python, dictionaries (often referred to as maps in other programming languages) are data structures that store key-value pairs. If you have a dictionary and you wish to find keys that correspond to values greater than 100, you can achieve this by using a simple loop or a list comprehension.
1. Using a For Loop
Here’s a straightforward approach using a for loop:
data = {
'a': 50,
'b': 150,
'c': 200,
'd': 75,
}
keys_with_values_over_100 = []
for key, value in data.items():
if value > 100:
keys_with_values_over_100.append(key)
print(keys_with_values_over_100)
['b', 'c']
In this approach, we initialize an empty list, keys_with_values_over_100. We then iterate over each key-value pair in the dictionary using data.items(). If the value is greater than 100, we append the key to our list.
2. Using List Comprehension
List comprehensions offer a more concise way to achieve the same result:
data = {
'a': 50,
'b': 150,
'c': 200,
'd': 75,
}
keys_with_values_over_100 = [key for key, value in data.items() if value > 100]
print(keys_with_values_over_100)
Output:
['b', 'c']
This list comprehension does exactly what the for loop did, but in a more succinct way. It iterates over each key-value pair in the dictionary and, if the value is greater than 100, adds the key to the resulting list.