如何删除列表中的dict(JSON对象)?

时间:2018-12-05 07:43:53

标签: python

我要删除的电影发行与我的地区发行列表中的m_y(月_年,例如12_2018)不同。我将其完整的电影对象传递给delete方法,以从列表中删除该对象,这是我的代码:

def remove_release_object(self, release_object, month_year):
    # Quick fix, to delete this exact item, set ti back
    release_object['m_y'] = month_year
    if release_object['region'] == 1:
        self.releases[month_year]["europe"].remove(release_object)
    if release_object['region'] == 2:
        self.releases[month_year]["north_america"].remove(release_object)
    if release_object['region'] == 3:
        self.releases[month_year]["australia"].remove(release_object)
    if release_object['region'] == 4:
        self.releases[month_year]["new_zealand"].remove(release_object)
    if release_object['region'] == 5:
        self.releases[month_year]["japan"].remove(release_object)
    if release_object['region'] == 8:
        # Worldwide release really only applies to the big region (na, eu, jp, aus, nz)
        self.releases[month_year]["europe"].remove(release_object)
        self.releases[month_year]["north_america"].remove(release_object)
        self.releases[month_year]["australia"].remove(release_object)
        self.releases[month_year]["new_zealand"].remove(release_object)
        self.releases[month_year]["japan"].remove(release_object)

在调用remove()之后,它仍然不起作用,我什至尝试设置一个快速修复程序来放置对象,就像最初看到旧的m_y一样,但是仍然没有任何东西被删除

1 个答案:

答案 0 :(得分:0)

要删除一个列表中的一项时,Python称为__eq__。这是帮助您理解的示例。

class A(object):
    def __eq__(self, other):
        print('eq was called')
        return True

l = [A()]
print(l)
l.remove(A())
print(l)

这意味着您必须保证release_object具有可比性,并且release_object等于movie_object。

另一方面,dict是可比较的,并且{'a':1}等于另一个{'a':1}。这意味着您的release_object不等于movie_object。您可以尝试:

l = [{'a': 1}]
print(l)
l.remove({'a': 1})
print(l)

因此,您应该检查代码,并检查release_object和movie_object之间的区别。