如何将字典[{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":4}]
转换为[{"a":1}, {"a":4}]
。我编写了一个函数,通过遍历列表来弹出不需要的键。
def pop_keys(dictionary, keys_to_pop):
for item in dictionary:
for key in keys_to_pop:
item.pop(key, None)
return dictionary
有没有更好,最快的方法来实现相同目标?
答案 0 :(得分:1)
您可以尝试
l1 = [{"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":4}]
keys_to_pop = {"b", "c"} # use a set for fast lookup
l2 = [{k:v for k,v in d.items() if k not in keys_to_pop} for d in l1] # use comprehension list and dictionary