Python字典迭代

时间:2011-06-13 15:39:45

标签: python dictionary

我有一个词典dict2,我希望通过它删除idlist中包含某些ID号的所有条目。 dict2[x]是一个列表列表(参见下面的示例dict2)。这是我到目前为止编写的代码,但它不会删除entry[1]中所有ID(idlist)的实例。有什么帮助吗?

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 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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']}