遍历字典列表并删除没有X键的字典

时间:2019-01-17 03:21:30

标签: python list dictionary

我有一个要在将其放入DataFrame之前要解析的JSON响应的列表。

在我的15,000个响应列表中,我要删除其中没有特定键的响应。

到目前为止,我删除某个元素后似乎一直在用循环玩有趣的事情,我不确定为什么。

如果我执行以下操作-它会正确找到3个匹配的15k匹配项,应将其删除。

Deleted! : 2591
Deleted! : 12306
Deleted! : 12307

-

try:
    for i in range(len(trans)):
        #print("checking for deletion: "+ str(i))
        if 'CashBooks' not in trans[i]:
            #del trans[i]
            print("Deleted! : " + str(i))
except Exception as e:
    print(str(e))
    print('passed')
    pass

但是,当我取消注释del时,会出现如下错误:

Deleted! : 2591
Deleted! : 12305
list index out of range
passed

列表很大,因此很难发布示例数据,但希望有人可以轻松发现我要去哪里。

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

您可以使用filter,这样会更快,并且在循环访问数据时不会编辑数据

def check_not_in(value):
    return 'Cashbooks' not in value

data = filter(check_not_in, trans)

#this is only to show what ones were deleted
def check_in(value):
    return 'Cashbooks' in value

deleted = filter(check_in, trans)
for _ in deleted: print("Deleted: {}".format(_))
相关问题