In this Python tutorial, we will see how to copy a Python dictionary without some of its keys with examples.
A Python dictionary can contain so many of the key-value pairs in it. Sometimes we need a similar dictionary to what we have but without some of its keys.
In this example, let me explain what I mean: we are on an e-commerce website with chocolates and cookies, and here we export things to an on-permissive shop. But he wants only the data for the chocolates to export.
In this case, we will keep the data with the e-commerce website and will only give the data of chocolates to the on-permissive shop.
cart = {
'kitkat': 14,
'dairy milk': 11,
'twix': 20,
'nutter butter': 7,
'milky way': 14,
'lindt': 15,
'oreo': 5
}
We have to make a copy of the parent dictionary and remove these two data from it so that the data of the parent dictionary remains unchanged.
Copy a Python dictionary without some of its keys
Let us check some of the methods to do this; they are:
- Using dictionary comprehension method with keys() function.
- Using dictionary comprehension method with items() function.
- Using for loop with if conditional statement.
There are some more methods where first we need to copy the Python dictionary and then remove the data from it; they are:
- Copy using dict() and remove using pop() method
- copy using copy() and remove using the del function
Method-1: Coping a Python dictionary without some of its keys using dictionary comprehension with key() function
As we all know, the dictionary comprehension method is used to craft a dictionary in Python, and, the keys() function returns the keys of a dictionary in Python.
In the example, we have car details on sale in 2022 shown on a pamphlet, we sold some of the cars in 2022. As we moved in 2023 we need similar details to show on the pamphlet but don’t need the sold cars.
cars_2022 = {
'Chevrolet Chevelle Malibu': '130.0',
'Buick Skylark 320': '165.0',
'Plymouth Satellite': '150.0',
'AMC Rebel SST': '150.0',
'Ford Torino': '140.0',
'Ford Galaxie 500': '198.0'
}
cars_2023 = {key:cars_2022[key] for key in cars_2022.keys() - {'Ford Torino', 'Ford Galaxie 500'}}
print('cars available in 2023 are: \n', cars_2023)
The output of this code in Python:
the facebook post left after deleting:
{'sam': {'Likes': 21, 'Comments': 2}, 'dave': {'Likes': 33, 'Comments': 8, 'Shares': 3}}
This way, we can use dict. comprehension and keys() to get the desired output in the Python dictionary.
Method-2: Coping a Python dictionary without some of its keys using dictionary comprehension with items() function
As we all know, the dictionary comprehension method is used to craft a dictionary in Python, and, the items() function returns a list containing a tuple for each key-value pair in Python.
For example, we have a Python dictionary with details of the Facebook posts posted by some of my friends. After some time some of them want to delete their post. But, I have to keep the details for both situations.
facebook_posts = {
'sam': {'Likes': 21, 'Comments': 2},
'josh': {'Comments': 4, 'Shares': 2},
'dave': {'Likes': 33, 'Comments': 8, 'Shares': 3},
'betty': {'Comments': 1, 'Shares': 1}
}
left_posts = {key: value for key, value in facebook_posts.items()
if key not in {'betty', 'josh'}}
print('the facebook post left after deleting: \n', left_posts)
The output of the above pile of code is:
the facebook post left after deleting:
{'sam': {'Likes': 21, 'Comments': 2}, 'dave': {'Likes': 33, 'Comments': 8, 'Shares': 3}}
As we can see, we got the required output using dictionary comprehension and the items() function in Python.
Method-3: Coping a Python dictionary without some of its keys using for loop and if conditional statement
As we know For loop is used to loop over a sequence and if is a conditional statement, used to decide whether a certain statement or block of statements will be executed or not.
Firstly we will create an empty dictionary to store the copied data. Then, we will loop over the key-value pair of the parent dictionary and check the condition if the keys which are not needed shouldn’t be copied.
Lastly, We will print the copied dictionary.
In this example, we have members (characters of Harry Potter) who are in Gryffindor’s house. some are teachers and some are students. we only need the data for students present in the Gryffindor house.
gryffindor_members = {
"Harry Potter": "Gryffindor",
"Ron Weasley": "Gryffindor",
"Hermione Granger": "Gryffindor",
"Albus Dumbledore": "Gryffindor"
}
gryffindor_students = {}
for key, value in gryffindor_members.items():
if key != 'Albus Dumbledore':
gryffindor_students[key] = value
print('students in Gryffindor house are: \n', gryffindor_students)
The output is:
students in Gryffindor house are:
{'Harry Potter': 'Gryffindor', 'Ron Weasley': 'Gryffindor', 'Hermione Granger': 'Gryffindor'}
As we can see we only got the student data from the Gryffindor house in Harry Potter. This way we can use for loop and an if conditional statement in a Python dictionary to copy the dictionary with some keys.
Method-4: Coping the Python dictionary using the dict() method and removing the keys with the pop() method
The dict() method returns a dictionary, while the pop() method removes the specified item from the Python dictionary. The pop() method accepts 1st argument as the keyname and 2nd as a value to return if the key does not exist.
Note: If the 2nd argument is not passed, and no item has the keyname provided, then the KeyError is raised.
Here, we will first copy the parent dictionary, then one by one we will remove the keys which are not required using the pop() method.
For example:: we have the details of the mail inbox with different kinds of mail. we have to give the details of the important emails only. So we need to clean the mail inbox.
mails_inbox = {
'read': 140,
'unread': 225,
'spam': 15,
'started': 45,
'advertisement': 650
}
updating_inbox = dict(mails_inbox)
updating_inbox.pop('spam')
updating_inbox.pop('advertisement')
print('mail inbox after cleaning: \n', updating_inbox)
The output of this code in Python is:
mail inbox after cleaning:
{'read': 140, 'unread': 225, 'started': 45}
Note: For deleting Multiple keys using the pop() method, we can use the for loop over the sequence, which will contain the names of the keys to be removed.
This way, we can easily get a copied Python dictionary without some keys using the pop() method and dict().
Method-5: Coping the Python dictionary using the copy() method and removing the keys with the del function
The copy() method returns a copy of the specified dictionary, while the del function removes the specified item from the Python dictionary. The del function accepts one argument at a time.
Here, we will first copy the parent dictionary and then remove the key one by one using the del function.
In the example, we have a store in the USA, which have chocolates and cookies in it. The shopkeeper wants to sell the chocolates on an e-commerce website. So, it copies the data, removes the names of cookies, and uploads it to the e-commerce site.
store = {
'galaxy': 10,
'twix': 12,
'oreo': 5,
'kisses': 15,
'swiss': 11,
'crackles': 14
}
e_commerce_store = store.copy()
del e_commerce_store['oreo']
del e_commerce_store['crackles']
print('Updated store on e-commerce sites: \n', e_commerce_store)
The output is:
Updated store on e-commerce sites:
{'galaxy': 10, 'twix': 12, 'kisses': 15, 'swiss': 11}
This way, we can easily use the copy and del method.
Read: Remove key from dictionary Python
Note: To remove multiple keys using the del function, we can use the for loop over a sequence containing the names of the keys to be removed.
Conclusion
In this tutorial, we have seen different ways to copy a Python dictionary without some of its keys. there are five different ways to do this.
You may also like:
- How to copy a dictionary in Python?
- How to copy specific keys in Python Dictionary
- Find Duplicate Keys in Dictionary Python
- convert a nested dictionary to json in Python
- Remove empty keys in dictionary Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.