Python 字典迭代

21 投票
2 回答
98773 浏览
提问于 2025-04-16 19:28

我有一个字典 dict2,我想遍历它并删除所有包含某些ID号码的条目,这些ID号码在 idlist 中。dict2[x] 是一个列表的列表(下面有 dict2 的示例)。我写的代码到目前为止,然而它并没有删除所有在 idlist 中的ID(entry[1])。有人能帮忙吗?

dict2 = {G1:[[A, '123456', C, D], [A, '654321', C, D], [A, '456123', C, D], [A, '321654', C, D]]}

idlist = ['123456','456123','321654']
for x in dict2.keys():
    for entry in dict2[x]:
        if entry[1] in idlist:
            dict2[x].remove(entry)
        if dict2[x] == []:
            del dict2[x]

最终 dict2 应该看起来像这样:

dict2 = {G1:[[A, '654321', C, D]]}

2 个回答

15

这里有一种使用集合的方法(注意,我需要把你变量中的A、B、C等改成字符串,把你的idlist中的数字改成真正的整数;另外,这种方法只有在你的ID是唯一的,并且不会出现在其他“字段”中时才能使用):

#!/usr/bin/env python
# 2.6 <= python version < 3

original = {
    'G1' : [
        ['A', 123456, 'C', 'D'], 
        ['A', 654321, 'C', 'D'], 
        ['A', 456123, 'C', 'D'], 
        ['A', 321654, 'C', 'D'],
    ]
}

idlist = [123456, 456123, 321654]
idset = set(idlist)

filtered = dict()

for key, value in original.items():
    for quad in value:
        # decide membership on whether intersection is empty or not
        if not set(quad) & idset:
            try:
                filtered[key].append(quad)
            except KeyError:
                filtered[key] = quad

print filtered
# would print:
# {'G1': ['A', 654321, 'C', 'D']}
34

你可以试试更简洁的版本吗?

for k in dict2.keys():
    dict2[k] = [x for x in dict2[k] if x[1] not in idlist]
    if not dict2[k]:
        del dict2[k]

撰写回答