Python | Remove multiple keys from dictionary - GeeksforGeeks (2024)

Last Updated : 06 Apr, 2023

Summarize

Comments

Improve

While working with Python dictionaries, we can have a utility in which we require to remove more than one key at once. This type of problem can occur while working in the Web Development domain with NoSQL Databases. Let’s discuss certain ways in which this task can be performed.

Remove multiple keys from a dictionary using del

Here, we are using a Python loop to iterate rem_list, while iterating if a key matches with the test_dict we delete it using the del keyword.

Python3

# initializing dictionary

test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}

# initializing Remove keys

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# Remove multiple keys from dictionary

for key in rem_list:

del test_dict[key]

# printing result

print("Dictionary after removal of keys : " + str(test_dict))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time complexity: O(n), where n is the length of the rem_list .
Auxiliary space: O(m), where m is the number of keys to be removed.

Remove multiple keys from a dictionary using not in + dict comprehension

Here, we are using dict comprehension and if condition to filter out the keys that have to remove from test_dict.

Python3

# initializing dictionary

test_dict = {'Gfg': 1, 'is': 2, 'best': 3,

'for': 4, 'CS': 5}

# initializing Remove keys

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# Remove multiple keys from dictionary

test_dict = {key: test_dict[key]

for key in test_dict if key not in rem_list}

# printing result

print("Dictionary after removal of keys : " + str(test_dict))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(m), where m is the number of keys to be removed from the dictionary

Remove multiple keys from a dictionary using pop()

In this method, we just use the Python pop() function which is used to remove a single key along with the list comprehension which iterates for the entire list to perform the remove operation.

Python3

# initializing dictionary

test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}

# initializing Remove keys

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# Using pop() + list comprehension

# Remove multiple keys from dictionary

[test_dict.pop(key) for key in rem_list]

# printing result

print("Dictionary after removal of keys : " + str(test_dict))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time complexity: O(n), where n is the number of keys in the dictionary,
Auxiliary space: O(1), as the program only uses a constant amount of extra space to store the rem_list and some temporary variables.

Remove multiple keys from a dictionary using items()

In this method, rather than the removal of keys, we reconstruct the dictionary using the dict function, by extracting key and value pairs using items() and iterating over them using list comprehension.

Python3

# initializing dictionary

test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}

# initializing Remove keys

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# Using items() + list comprehension + dict()

# Remove multiple keys from dictionary

res = dict([(key, val) for key, val in

test_dict.items() if key not in rem_list])

# printing result

print("Dictionary after removal of keys : " + str(res))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. The loop used in the list comprehension runs n times, and each iteration takes constant time to check if the key is in the rem_list and access the value associated with the key.

Auxiliary Space: O(m), where m is the number of keys to be removed from the dictionary. The space required to store the rem_list is O(m), and the space required to store the resulting dictionary is also O(m) because at most m key-value pairs are added to it.

Method 5: Using a for loop and the dict.pop() method

In this method, we use a for loop to iterate over the keys we want to remove and call dict.pop() method with that key to remove it from the dictionary. We pass None as the second argument to pop() method to handle the case when a key is not present in the dictionary.

Python3

test_dict = {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# remove multiple keys from dictionary using a for loop and dict.pop()

for key in rem_list:

test_dict.pop(key, None)

# printing result

print("Dictionary after removal of keys : " + str(test_dict))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time Complexity: O(k), where k is the number of keys we want to remove from the dictionary.

Space Complexity: O(1), as we do not use any additional data structure to store the intermediate results.

Method 6 : Using a dictionary comprehension.

step-by-step approach:

  1. Create a new dictionary comprehension that includes only the key-value pairs from the original dictionary that do not have keys in the rem_list. This can be done by iterating over the items() of the dictionary and checking if the key is not in the rem_list.
  2. Assign the new dictionary comprehension to the original dictionary variable to update it with the new key-value pairs.

Python3

test_dict = {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}

rem_list = ['is', 'for', 'CS']

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# remove multiple keys from dictionary using dictionary comprehension

test_dict = {k: v for k, v in test_dict.items() if k not in rem_list}

# printing result

print("Dictionary after removal of keys : " + str(test_dict))

Output

The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}Dictionary after removal of keys : {'Gfg': 1, 'best': 3}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), because a new dictionary is created and stored in memory.



manjeet_04

Python | Remove multiple keys from dictionary - GeeksforGeeks (2)

Improve

Next Article

Python - Remove Kth key from dictionary

Please Login to comment...

Python | Remove multiple keys from dictionary - GeeksforGeeks (2024)
Top Articles
Trade Deficit: What It Is and Its Effect on the Market
How is Lightyear regulated? | Lightyear
Garrison Blacksmith Bench
Sound Of Freedom Showtimes Near Governor's Crossing Stadium 14
Toyota Campers For Sale Craigslist
Us 25 Yard Sale Map
Caroline Cps.powerschool.com
DENVER Überwachungskamera IOC-221, IP, WLAN, außen | 580950
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
Produzione mondiale di vino
Maxpreps Field Hockey
Shariraye Update
2135 Royalton Road Columbia Station Oh 44028
Hope Swinimer Net Worth
OSRS Dryness Calculator - GEGCalculators
Dallas’ 10 Best Dressed Women Turn Out for Crystal Charity Ball Event at Neiman Marcus
How To Cut Eelgrass Grounded
Comics Valley In Hindi
Swgoh Blind Characters
Water Trends Inferno Pool Cleaner
Understanding Genetics
Why Are Fuel Leaks A Problem Aceable
WRMJ.COM
Tinyzonehd
Robotization Deviantart
They Cloned Tyrone Showtimes Near Showbiz Cinemas - Kingwood
Mami No 1 Ott
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
Craigslist Maryland Baltimore
Unlock The Secrets Of "Skip The Game" Greensboro North Carolina
John F Slater Funeral Home Brentwood
Cl Bellingham
2700 Yen To Usd
Puretalkusa.com/Amac
The best bagels in NYC, according to a New Yorker
Flipper Zero Delivery Time
Karen Wilson Facebook
manhattan cars & trucks - by owner - craigslist
Hazel Moore Boobpedia
Suntory Yamazaki 18 Jahre | Whisky.de » Zum Online-Shop
15 Best Places to Visit in the Northeast During Summer
Greg Steube Height
Frontier Internet Outage Davenport Fl
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Sacramentocraiglist
Learn4Good Job Posting
Rocket League Tracker: A useful tool for every player
Theatervoorstellingen in Nieuwegein, het complete aanbod.
San Diego Padres Box Scores
Smoke From Street Outlaws Net Worth
Hsi Delphi Forum
Coleman Funeral Home Olive Branch Ms Obituaries
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5965

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.