Python - Copy dictionary using Dictionary Comprehension
Copy dictionary using Dictionary Comprehension in Python
In this tutorial, you will learn how to use Dictionary Comprehension to copy a given dictionary to a new dictionary in Python.
The syntax of dictionary comprehension to copy a given dictionary, say input_dict, is
{key: value for key, value in input_dict.items()}
input_dict.items() returns a dict_items iterable where we get access to both key and value during each iteration.
Example
In the following program, we take a dictionary in input_dict. This is our input iterable in the dictionary comprehension. We shall add each of the item in this iterable input_dict to the new dictionary output_dict using dictionary comprehension.
Python Program
input_dict = {
'foo': 12,
'bar': 14,
'moo': 16
}
output_dict = {key: value for key, value in input_dict.items()}
print(output_dict)
Output
{'foo': 12, 'bar': 14, 'moo': 16}
Summary
In this tutorial of Dictionary Comprehension in Python, we have seen how to copy a given dictionary into a new dictionary using dictionary comprehension, with examples.