Create New Dictionary from Existing Dictionary in Python

This tutorial will discuss about unique ways to create new dictionary from existing dictionary in Python.

Table Of Contents

Using Dictionary Comprehension

Suppose we have an existing dictionary,

oldDict = { 'Ritika': 34,
            'Smriti': 41,
            'Mathew': 42,
            'Justin': 38}

Now we want to create a new dictionary, from this existing dictionary. For this, we can iterate over all key-value pairs of this dictionary, and initialize a new dictionary using Dictionary Comprehension. Like this,

# Create a new dictionary from old dictionary
newDict = {key: value for key, value in oldDict.items()}

It will create a copy of dictionary, and any modification in one dictionary will have no effect on another dictionary.

Let’s see the complete example,

# Create a Dictionary
oldDict = { 'Ritika': 34,
            'Smriti': 41,
            'Mathew': 42,
            'Justin': 38}

# Create a new dictionary from old dictionary
newDict = {key: value for key, value in oldDict.items()}

# Print the new Dictionary
print(newDict)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Using Dictionary copy() method

To create a new dictionary, from an existing dictionary, we can call the copy() method on old dictionary. It will return a shallow copy of the existing dictionary. Any modification in one dictionary will have no effect on another dictionary.

Let’s see the complete example,

# Create a Dictionary
oldDict = { 'Ritika': 34,
            'Smriti': 41,
            'Mathew': 42,
            'Justin': 38}

# Create a new dictionary from old dictionary
newDict = oldDict.copy()

# Print the new Dictionary
print(newDict)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Summary

We learned about two ways to create a new Dictionary from another Dictionary in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top