Python字典迭代

问题描述

| 我有一个字典
dict2
,我想对其进行遍历并删除
idlist
中包含某些ID号的所有条目。 “ 2”是列表的列表(请参见下面的示例dict2)。这是我到目前为止编写的代码,但是并不能删除
idlist
中所有ID(
entry[1]
)的实例。有什么帮助吗?
dict2 = {G1:[[A,\'123456\',C,D],[A,\'654321\',\'456123\',\'321654\',D]]}

idlist = [\'123456\',\'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,D]]}
    

解决方法

        尝试更清洁的版本?
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唯一且在其他“字段”):
#!/usr/bin/env python
# 2.6 <= python version < 3

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

idlist = [123456,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\',\'D\']}