Python字典迭代

Python dictionary iteration

我有一本字典dict2,我想通过它来检索和删除idlist中包含特定ID号的所有条目。dict2[x]是一个列表列表(参见下面的示例dict2)。这是我迄今为止编写的代码,但它并没有删除idlist中的所有ID实例(entry[1])。有什么帮助吗?

1
2
3
4
5
6
7
8
9
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应该是这样的:

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


试试更干净的版本吧?

1
2
3
4
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]


一种使用集合的方法(请注意,我需要将变量a、b、c等更改为字符串,并将idlist中的数字更改为实际整数;而且,这仅在ID唯一且不出现在其他"字段"中时有效):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/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']}