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

Since the key has several values, and I want to delete the one that matches the key itself? That is, I have a jumps dictionary:

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

And I want to delete the value 'I6' using the key 'I6' , and also 'T8' using the key 'T8' . How can i do this? I mix in parsing strings and values.

+7
python dictionary list frame
source share
5 answers

You can use a single line interface with word understanding and list comprehension:

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

This leads to:

 >>> {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 items from lists that are equal to the key. In addition, the removal process is performed for everyone .

The code works as follows: we iterate over each key-value pair k,v in the jumps dictionary. Then for each such pair we build the key in the resulting dictionary and associate [vi for vi in v if k != vi] . This is an understanding of the list, where we filter out all the values ​​of v that are equal to k . Thus, only vi (in that order) k != vi remains.

+9
source share
 for key in jumps: jumps[key].remove(key) 
+5
source share

There is a built-in command called remove that will remove an item from the list. We can start by accessing an element from our dictionary using a string key. This value is a list, and we can use the remove command.

Here is your list to demonstrate:

 jumps = { 'I6': [ # we are accessing this value that happens to be a list 'H6', 'I6', #then Python will sort for and remove this value 'I5' ], 'T8' : [ 'T6', 'S6', 'T8' ] } jumps = {'I6': ['H6', 'I6', 'I5'], 'T8' : ['T6', 'S6', 'T8']} jumps['I6'].remove('I6') jumps['T8'].remove('T8') print(jumps) 
+3
source share

Works for me

 jumps = {'I6': ['H6', 'I6', 'I5'], 'T8' : ['T6', 'S6', 'T8']} key = 'I6' if key in jumps[key]: jumps[key].remove(key) print(jumps) 
0
source share

Another possible way could be:

 {vals.remove(val) for key,vals in jumps.items() for val in vals if val == key} 

Since it refers to a list of values ​​or an array, deletion from the list will affect the values ​​of jumps .

0
source share

All Articles