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.
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.
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.
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.
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.
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 vi
s remain (in that order) that are k != vi
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With