dclobato dclobato - 3 months ago 7
Python Question

Slicing a list of dictionaries and removing one key

I have a list of dictionaries, like the one below:

l = [ { "a": 10, "b": 4, "c": 6 },
{ "a": 10, "b": 6, "c": 8 },
{ "a": 13, "b": 3, "c": 9 },
{ "a": 12, "b": 5, "c": 3 },
{ "a": 11, "b": 7, "c": 1 } ]


Now, I want to slice it and have a list only with dictionaries where the key
a
has value
10
, but removing the key
a
from the dictionary. Like the list below:

nl = [ { "b": 4, "c": 6 },
{ "b": 6, "c": 8 } ]


I can do this by processing
l
twice:

l[:] = [d for d in l if d.get("a") == 10]
nl = []
for c in l:
del c["a"]
nl.append(c)


Is there a more straightforward way to accomplish this?

Answer

There may be a better way, but you can do a nested dict comprehension:

[{k:d[k] for k in d if k!="a"} for d in l if d.get("a") == 10]
Comments