首页 > 解决方案 > 从具有特定键值的字典列表中删除元素

问题描述

我有一堆地理位置保存为字典列表。其中一个关键是国家 ID,我想删除所有国家 ID 不是 112 的位置。我写了这段代码。由于某种原因,它删除了大多数非 112 条目,但并未删除所有条目。这是我为此过滤编写的循环:

counter = 0
i=0
while counter < len(CS_list):
    country = CS_list[i]["AddressInfo"].get("CountryID")
    if country != 112:
        CS_list.pop(i)
    else:
        i += 1
    counter += 1

是运行此循环后的列表。正如你所看到的,仍然有一些非 112,尽管很多这样的条目已被删除。这真的让我很困惑。知道为什么会这样吗?

编辑: 是输入列表元素的示例。运行循环后,我希望拥有相同的列表,但没有国家 ID 不同于 112 的所有元素。

标签: pythondictionarykey

解决方案


通常,您只需构建一个仅包含您想要的元素的新列表。

countries = [
    {'AddressInfo': {'CountryID': 112}},
    {'AddressInfo': {'CountryID': 8}},
    {'AddressInfo': {'CountryID': 2}},
    {'AddressInfo': {'CountryID': 4}},
    {'AddressInfo': {'CountryID': 112}},
]
countries = [
    country for country in countries
    if country.get('AddressInfo', {}).get('CountryID') == 112
]  
print(countries)

如果您明确想要从现有列表中删除这些条目,您可以将列表推导的结果作为切片分配给原始列表:

countries[:] = [
    country for country in countries
    if country.get('AddressInfo', {}).get('CountryID') == 112
]

推荐阅读