How to Copy Specific Keys from a Python Dictionary?

Estimated read time 1 min read

To copy specific keys from a Python dictionary, you can create a new dictionary with a dictionary comprehension that filters out the unwanted keys. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
keys_to_copy = ['a', 'c', 'e']
new_dict = {k: v for k, v in my_dict.items() if k in keys_to_copy}
print(new_dict)

Output:

{'a': 1, 'c': 3, 'e': 5}

In this example, my_dict is the original dictionary, and keys_to_copy is a list of the keys to copy. The dictionary comprehension creates a new dictionary new_dict with only the keys that are in keys_to_copy.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply