[英]How to remove a particular value from the list of values using Python
I am trying to remove the particular value from the list of key. 我正在尝试从键列表中删除特定的值。 I got Type error.
我收到类型错误。 I wrote function to add and remove the key.
我编写了添加和删除键的函数。 need to remove a particular value from the key
需要从密钥中删除特定值
class my_dict(dict):
def add(self, key, value):
self.setdefault(key, []).append(value)
def remove_key(self, key):
del self[key]
#Error part
def remove_value(self,key,value):
for value in dict.values():
if v in value:
value.remove(v)
dict_obj = my_dict()
dict_obj.add('key1', 'value1')
dict_obj.add('key2', 'value2')
dict_obj.add('key1', 'value3')
print(dict_obj)
>>{'key1': ['value1', 'value3'], 'key2': ['value2']}
dict_obj.remove_value('key1','value3')
print(dict_obj)
My Out 我的出
TypeError: descriptor 'values' of 'dict' object needs an argument
Desired Output 期望的输出
>>{'key1': ['value1'], 'key2': ['value2']}
You've got a couple problems in: 您在以下方面遇到了一些问题:
def remove_value(self,key,value):
for value in dict.values():
if v in value:
value.remove(v)
dict.values()
, not self.values()
; dict.values()
而不是self.values()
; the former is trying to call dict.values
with no dict
instance to operate on dict
实例的情况下调用dict.values
value
, and one replaces the other (while using v
without ever naming anything v
) value
,而其中一项则替换了另一件事(在使用v
从未命名v
) Minimal fix would be: 最小修复是:
def remove_value(self,key,v): # Name argument v to match test and remove
for value in self.values(): # Call values on self
if v in value:
value.remove(v)
Slightly more readable fix (that would also limit removal to the specified key
, which I'm guessing was the intent, since you receive a key
argument) would be: 可读性更强的修复(这也将删除限制为指定的
key
,我想这是意图,因为您收到key
参数)将为:
def remove_value(self, key, toremove):
try:
self[key].remove(toremove)
except (KeyError, ValueError):
pass
else:
if not self[key]:
del self[key]
Remove the try
/ except
block if you want non-existent keys or values to raise KeyError
or ValueError
respectively. 如果要不存在的键或值分别引发
KeyError
或ValueError
删除try
/ except
块。 Remove the else
block if you want to leave a key in place even if all values are removed. 如果即使所有值都已删除,也要保留键,请删除
else
块。
you need to remove it from self[key].value
if value in self[key]
: 如果
self[key].value
value in self[key]
则需要将其从self[key].value
删除:
def remove_value(self,key,value):
if value in self.get(key, []):
self[key].remove(value)
But similar to your previous related question , this seems like you'd be better suited using defaultdict
than trying to monkeypatch your own dict-like object. 但是类似于您先前的相关问题 ,似乎您最好使用
defaultdict
比尝试猴子补丁自己的类似dict的对象更好。
from collections import defaultdict
mydict = defaultdict(list)
mydict['key1'].append('value1')
mydict['key1'].append('value3')
mydict['key2'].append('value2')
if 'value3' in mydict['key1']:
mydict['key1'].remove('value3')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.