How to Keep One Key in a Dictionary While Removing All Others in Python?

Estimated read time 1 min read

To keep one key in a dictionary while removing all others in Python, you can create a new dictionary with only the desired key-value pair. Here is an example code snippet that keeps one key in a dictionary while removing all others:

original_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Keep only one key in the dictionary
new_dict = {"key1": original_dict["key1"]}

print(new_dict)  # Output: {'key1': 'value1'}

In this code, we define an original dictionary (original_dict) that contains key-value pairs.

Next, we create a new dictionary (new_dict) by assigning only the desired key-value pair to it. In this example, we keep only the "key1" key-value pair from the original dictionary.

Finally, we print the new dictionary (new_dict) that contains only the desired key-value pair.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply