Python字典迭代

21
我有一个字典 dict2,我想要遍历它并删除所有包含idlist中特定ID编号的条目。 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个回答

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]

请注意,您不能在迭代字典时修改它(https://dev59.com/im435IYBdhLWcg3wfQJ9#5385075),因此@ marsx 正确地迭代了 dict2.keys() - Ben Hoyt
@benhoyt - 你是对的;我最初把它拿掉是因为我忘记了 del,但后来加上了 del 却没有换回来。 :) - Amber
@Amber 我打错了,但是ID号码都是字符串。我尝试了你的代码,但是出现了这个错误 dict2[x] = [x for x in dict2[k] if x[1] not in idlist] TypeError: list objects are unhashable。我不知道这是否有所不同,但是真正的dict2也包含datetime对象和其他列表。 - marsx
如果你遇到了这个错误,那么你的 dict2 比你在这里写的多了一层嵌套,或者列表中使用了错误的索引。 - Amber
@Amber 是否应该是 dict2[k] = [x for x in dict2[k] if x[1] not in idlist]?如果你将列表称为 x,那么 dict2[x] 就没有意义了。 - marsx

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']}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接