简体   繁体   English

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

[英]How to delete dict (JSON object) in a list?

I'm deleting the movie releases which have a different m_y (month_year eg 12_2018) from my region releases list.我正在从我的地区发行列表中删除具有不同 m_y(month_year,例如 12_2018)的电影发行。 I pass its complete movie object in the delete method to remove that object from the list(s), here's my code:我在 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)

After calling remove() it still doesn't work, I even tried to set a quick fix to put the object like it was initially with seeting the old m_y, but still nothing gets removed调用 remove() 后它仍然不起作用,我什至尝试设置一个快速修复来放置对象,就像它最初使用旧的 m_y 一样,但仍然没有被删除

Python called __eq__ when you want to remove one item in one list.当您想删除一个列表中的一项时,Python 会调用__eq__ This is an example help you understand it.这是一个帮助你理解它的例子。

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

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

That means you have to promise release_object is comparable and release_object equal to movie_object.这意味着你必须保证 release_object 是可比较的并且 release_object 等于 movie_object。

Another point, dict is comparable and {'a': 1} is equal to another {'a': 1}.还有一点, dict 是可比的,{'a': 1} 等于另一个 {'a': 1}。 That means your release_object not equal to movie_object.这意味着您的 release_object 不等于 movie_object。 You can try:你可以试试:

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

So you should check your code, and check the difference between release_object and movie_object.所以你应该检查你的代码,并检查 release_object 和 movie_object 之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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