Python 从具有特定键值的字典列表中删除元素

Python 从具有特定键值的字典列表中删除元素,python,dictionary,key,Python,Dictionary,Key,我有一大堆地理位置保存为字典列表。其中一个关键是国家ID,我想删除所有国家ID不同于112的位置。我写了这段代码。出于某种原因,它会删除大部分非112项,但不会删除所有项。以下是我为此过滤编写的循环: counter = 0 i=0 while counter < len(CS_list): country = CS_list[i]["AddressInfo"].get("CountryID") if country != 112:

我有一大堆地理位置保存为字典列表。其中一个关键是国家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
计数器=0
i=0
当计数器
是运行此循环后的列表。正如您所看到的,尽管许多这样的条目已被删除,但仍有一些非112条目保留下来。这真让我困惑。知道为什么会这样吗

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

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

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
]

通常,您只需构建一个只包含所需元素的新列表

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
]

在问题描述和预期输出中发布列表。如果列表太长,只需输入和输出一个示例。将列表张贴在问题描述和预期输出中。如果列表太长,只需输入和输出一个示例。谢谢,它似乎正在工作!我还是不明白为什么它以前不起作用。谢谢你,它现在似乎起作用了!但我还是不明白为什么它以前不起作用。