Python: how to remove a value from a dict if it exactly matches the key?
因为该键有多个值,所以我想删除与该键本身相同的值?也就是说,我有一本字典
1 | jumps = {'I6': ['H6', 'I6', 'I5'], 'T8' : ['T6', 'S6', 'T8']} |
我想删除
您可以在字典理解和列表理解中使用一行代码:
1 | result = {k:[vi for vi in v if k != vi] for k,v in jumps.items()} |
这将导致:
1 2 | >>> {k:[vi for vi in v if k != vi] for k,v in jumps.items()} {'T8': ['T6', 'S6'], 'I6': ['H6', 'I5']} |
请注意,您将从列表中删除与键相同的所有元素。此外,对所有键执行删除过程。
代码的工作原理如下:我们迭代
1 2 | for key in jumps: jumps[key].remove(key) |
有一个名为
下面是您要演示的列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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) |
另一种可能的方法是:
1 | {vals.remove(val) for key,vals in jumps.items() for val in vals if val == key} |
因为它引用的是值列表或数组,所以从列表中删除会影响
为我工作
1 2 3 4 5 6 7 8 | jumps = {'I6': ['H6', 'I6', 'I5'], 'T8' : ['T6', 'S6', 'T8']} key = 'I6' if key in jumps[key]: jumps[key].remove(key) print(jumps) |