Sometimes we need to iterate through only specific keys in a dictionary rather than going through all of them. We can use various methods to iterate through specific keys in a dictionary in Python.
Using dict.get() Method
When we're not sure whether a key exists in the dictionary and don't want to raise a KeyError, we can use the get() method. This method returns None (or a default value) if the key doesn't exist.
d = {"a": 1, "b": 2, "c": 3, "d": 4}
# List of keys we want to check
keys = ["a", "b", "e", "d"]
# Iterate through specific keys using get()
for key in keys:
# Returns None if key doesn't exist
value = d.get(key)
if value is not None:
print(key, value)
Output
a 1 b 2 d 4
Let's explore various other methods that helps to Iterate Through Specific Keys in a Dictionary in Python.
Table of Content
Using a Simple Loop with in Keyword
The easiest and most efficient way to loop through specific keys is by checking if the key is in the dictionary. We can do this by using a simple for loop with the in keyword.
d = {"a": 1, "b": 2, "c": 3, "d": 4}
# List of keys we want to iterate over
keys = ["a", "b", "e", "d"]
for key in keys:
# Check if key exists in the dictionary
if key in d:
print(key, d[key])
Output
a 1 b 2 d 4
Using Dictionary Comprehension
By using Dictionary Comprehension, we can create a new dictionary with specific keys and their corresponding values. This is a concise way to filter and create a new dictionary.
d = {"a": 1, "b": 2, "c": 3, "d": 4}
# List of keys we want to keep
keys = ["a", "c"]
# Create a new dictionary with specific keys
new = {key: d[key] for key in keys if key in d}
print(new)
Output
{'a': 1, 'c': 3}
Using filter() and lambda
The filter() function is used to create an iterator of keys from the list keys that also exist in dictionary d. We use a lambda function to check if each key is present in d. Then we loop through the filtered keys and print their values.
d = {"a": 1, "b": 2, "c": 3, "d": 4}
# List of keys to filter
keys = ["a", "c", "d"]
# Use filter to get keys that are in d
new_keys = filter(lambda k: k in d, keys)
# Iterate through filtered keys
for key in new_keys:
print(key, d[key])
Output
a 1 c 3 d 4