简体   繁体   中英

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.

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

result = {:[vi for vi in  if  != vi] for  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 .

for key in jumps:
    jumps[key].remove(key)

There is a built in command, called remove that will remove an item from a list. We can start by accessing the element from our dictionary by using a string key. That value, happens to be a list, that we can then use the remove command on.

Here's 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)

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)

The other possible way might be:

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

Since, it is referencing to the values list or array, the removal from list will affect in values of jumps .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM