How to Slice a Dictionary in Python?

Estimated read time 2 min read

Dictionaries in Python are collections of key-value pairs, and as such, they do not support slicing. However, you can extract a subset of key-value pairs from a dictionary using dictionary comprehension or the items() method.

Here’s an example of using dictionary comprehension to extract a subset of key-value pairs from a dictionary:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# extract key-value pairs where the key is 'b' or 'd'
new_dict = {k: v for k, v in my_dict.items() if k in ['b', 'd']}
print(new_dict) # Output: {'b': 2, 'd': 4}

In this example, the dictionary comprehension {k: v for k, v in my_dict.items() if k in ['b', 'd']} creates a new dictionary containing all the key-value pairs (k, v) in my_dict where the key k is ‘b’ or ‘d’. The resulting subset is a new dictionary containing the key-value pairs ‘b’: 2 and ‘d’: 4.

Alternatively, you can use the items() method of the dictionary to extract a subset of key-value pairs that meet certain criteria. For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# extract key-value pairs where the value is even
new_dict = {k: v for k, v in my_dict.items() if v % 2 == 0}
print(new_dict) # Output: {'b': 2, 'd': 4}

In this example, the dictionary comprehension {k: v for k, v in my_dict.items() if v % 2 == 0} creates a new dictionary containing all the key-value pairs (k, v) in my_dict where the value v is even. The resulting subset is a new dictionary containing the key-value pairs ‘b’: 2 and ‘d’: 4.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply