Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to remove a value from a dict if it exactly matches the key?

Being that the key has multiple values and I want to remove the one that is the same as the key itself? That is, I have a dictionary jumps:

jumps = {'I6': ['H6', 'I6', 'I5'], 'T8' : ['T6', 'S6', 'T8']}

And I want to delete the value 'I6' from the 'I6' key and also 'T8' from the 'T8' key. How could I do this? I'm getting mixed up in parsing the strings versus the values.

like image 258
Cora Coleman Avatar asked Mar 20 '17 01:03

Cora Coleman


People also ask

Can you remove key value pairs from a dictionary and if so how?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

Can we remove key value pair from dictionary Python?

Method 1: Remove a Key from a Dictionary using the del The del keyword can be used to in-place delete the key that is present in the dictionary in Python.

How do you delete something from the dictionary while iterating?

First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.

Which method removes the element with the specified key from the dictionary?

Python Dictionary pop() Method Python pop() method removes an element from the dictionary. It removes the element which is associated to the specified key. If specified key is present in the dictionary, it remove and return its value.


1 Answers

You can use a one-liner with both dictionary comprehension and list comprehension:

result = {k:[vi for vi in v if k != vi] for k,v in jumps.items()}

This results in:

>>> {k:[vi for vi in v if k != vi] for k,v in jumps.items()}
{'T8': ['T6', 'S6'], 'I6': ['H6', 'I5']}

Note that you will remove all elements from the lists that are equal to the key. Furthermore the remove process is done for all keys.

The code works as follows: we iterate over every key-value pair k,v in the jumps dictionary. Then for every such pair, we construct a key in the resulting dictionary, and associate [vi for vi in v if k != vi] with it. That is a list comprehension where we filter out all values of v that are equal to k. So only the vis remain (in that order) that are k != vi.

like image 113
Willem Van Onsem Avatar answered Oct 18 '22 20:10

Willem Van Onsem