Sunday, September 8, 2024
HomePythonFind out how to Take away A number of Keys from a...

Find out how to Take away A number of Keys from a Python Dictionary – Finxter


Abstract: You should use one among these strategies to delete a number of keys from a dictionary Python –
(1) Iterate throughout the listing of keys to be deleted and use the syntax del dict[‘key’]
(2) Iterate throughout the listing of keys to be deleted and name the dictionary.pop(key)technique.
(3) Remove unrequired keys and reconstruct the unique dictionary utilizing a dictionary comprehension.
(4) Use map and pop strategies.

Downside Formulation

Think about that you’ve a Python dictionary that has sure key-value pairs. How will you take away a number of keys from the given dictionary?

Eradicating a number of keys from a Python dictionary results in the deletion of all of the specified key-value pairs with respect to the required keys leaving the dictionary with solely these key-value pairs that haven’t been eliminated. Allow us to visualize the given downside with the assistance of an instance.

Instance:

Given:
my_dictionary = {‘key_1’: ‘value_1’, ‘key_2’: ‘value_2’, ‘key_3’: ‘value_3’, ‘key_4’: ‘value_4’, ‘key_5’: ‘value_5’}
Problem: Take away the keys: ‘key_1’ and ‘key_3’
Anticipated Output:
{‘key_2’: ‘value_2’, ‘key_4’: ‘value_4’, ‘key_5’: ‘value_5’}

Associated Learn: Delete an Ingredient in a Dictionary | Python

With out additional ado, let’s dive into the options to the programming problem.

⦿ Technique 1: Utilizing a ‘For Loop’ and the ‘del’ Key phrase

The del key phrase alongside, with the required key, permits us to take away components from a dictionary.

Strategy: Retailer the keys to be eliminated in a listing after which use a ‘for loop’ to iterate throughout all the weather of this. Now entry the weather throughout the given dictionary utilizing every key and delete them utilizing the “del” key phrase utilizing the syntax: del dictinary[key]

Code:

my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
remove_keys = ['key_1', 'key_3']
for key in remove_keys:
    del my_dictionary[key]

print(my_dictionary)

Output:

{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}

⦿ Technique 2: Utilizing a ‘For Loop’ and the ‘pop’ Key phrase

Strategy: Retailer the keys to be eliminated inside a listing. Then, use a for loop throughout the listing of keys, and at every iteration, name the dictionary.pop(key) technique to take away a particular key from the given dictionary.

Code:

my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
remove_keys = ['key_1', 'key_3']
for key in remove_keys:
    my_dictionary.pop(key)

print(my_dictionary)

Output:

{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}

One-Liner: There’s a extra concise approach of formulating the above resolution in a single line of code. Right here’s do it:

# Given Information
my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
# One-Liner
[my_dictionary.pop(key) for key in ['key_1', 'key_3']];print(my_dictionary)

Strategy: Iterate throughout all of the keys within the dictionary besides those that you just wish to delete utilizing a dictionary comprehension after which retailer solely the required key-values within the dictionary. Subsequently, this system routinely eliminates the key-value pairs to be faraway from the dictionary.

Code:

my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
# One-liner
my_dictionary = {i: my_dictionary[i] for i in my_dictionary if i not in ['key_1', 'key_3']}
# Show consequence
print(my_dictionary)

Output:

{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}

Rationalization: Let’s dissect the one-liner to know the way it works. The expression shops the key-value pairs within the dictionary that you do not need to delete. To remove the required keys we have now the context variable “i” that denotes every key that needs to be eradicated. The for loop permits you to solely contemplate the required keys with the assistance of the conditional if assertion which lets you ignore the required keys. Thus, you possibly can consider this as an remove and conquer method!

An alternate formulation that makes use of an analogous logic is as follows:

my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
my_dictionary= dict([(key, val) for key, val in my_dictionary.items() if key not in ['key_1', 'key_3']])
print(my_dictionary)

However earlier than we transfer on, I’m excited to current you my new Python e book Python One-Liners (Amazon Hyperlink).

If you happen to like one-liners, you’ll LOVE the e book. It’ll train you every little thing there may be to learn about a single line of Python code. Nevertheless it’s additionally an introduction to pc science, information science, machine studying, and algorithms. The universe in a single line of Python!

The e book was launched in 2020 with the world-class programming e book writer NoStarch Press (San Francisco).

Hyperlink: https://nostarch.com/pythononeliners

⦿ Technique 4: Utilizing pop and map

This may not be probably the most Pythonic resolution. However, it solves the aim and yields us the output that we want.

Strategy: The concept is to retailer the keys to be eradicated in a listing after which use the map() technique. Cross the dictionary.pop() technique as the primary argument to the map technique whereas the second argument needs to be an iterable and on this case the second argument/iterable is the listing containing the keys to be eliminated.

Code:

my_dictionary = {
    'key_1': 'value_1',
    'key_2': 'value_2',
    'key_3': 'value_3',
    'key_4': 'value_4',
    'key_5': 'value_5'
}
remove_keys = ['key_1', 'key_3']
listing(map(my_dictionary.pop, remove_keys))
print(my_dictionary)

TIDBIT: The map() operate transforms a number of iterables into a brand new one by making use of a “transformator operate” to the i-th components of every iterable. The arguments are the transformator operate object and a number of iterables. If you happen to cross n iterables as arguments, the transformator operate have to be an n-ary operate taking n enter arguments. The return worth is an iterable map object of remodeled, and presumably aggregated, components.

Learn extra about map technique right here: Python map() — Lastly Mastering the Python Map Perform [+Video]

Conclusions

We’ve efficiently conquered the given programming problem and solved it utilizing as many as 4 other ways. I hope this tutorial helped you. Please subscribe and keep tuned to unearth new ideas day by day.

Comfortable coding! 🙂


Finxter Laptop Science Academy

  • One of the vital sought-after abilities on Fiverr and Upwork is internet scraping. Make no mistake: extracting information programmatically from web sites is a essential life talent in right this moment’s world that’s formed by the online and distant work.
  • So, do you wish to grasp the artwork of internet scraping utilizing Python’s BeautifulSoup?
  • If the reply is sure – this course will take you from newbie to knowledgeable in Net Scraping.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments