handy way to get rid of some fields using list comprehension

Question:

So, imagine an item like so:

x = {"name":"blah",
     "this_must_go":"obsolette",
     "this_must_also_go":"unfixable",
     "type":4}

and I have lets say a list of 200 of these xes and I want to remove all this_must_go and this_must_also_go fields from all x in the list, no exception. I prefer using list comprehension if possible. Is there a one-liner or neat syntax to achieve this?

Asked By: Das Raf

||

Answers:

Use a list comprehension containing a dictionary comprehension.

fields_to_delete = {'this_must_go', 'this_must_also_go'}

new_list = [{k: v for k, v in x.items() if k not in fields_to_delete} 
            for x in original_list]
Answered By: Barmar

Be pythonic:

[
    {
        k: v
        for k, v in d.items() if k not in ['this_must_go', 'this_must_also_go']
    }
    for d in your_list
]
Answered By: Hanwei Tang

You could use the fact that dictionary keys act like sets and subtract the unwanted keys in a list comprehension.

to_drop = {'this_must_go', 'this_must_also_go'}

xs = [
    {"name":"blah1", "this_must_go":"obsolette", "this_must_also_go":"unfixable", "type":4},
    {"name":"blah2", "this_must_go":"obsolette", "this_must_also_go":"unfixable", "type":5},
    {"name":"blah3", "this_must_go":"obsolette", "this_must_also_go":"unfixable", "type":6}
]

[{k:x[k] for k in x.keys() - to_drop} for x in xs]

This will give new dicts in a list like:

[
  {'type': 4, 'name': 'blah1'},
  {'type': 5, 'name': 'blah2'},
  {'type': 6, 'name': 'blah3'}
]
Answered By: Mark

You could try this:

x = {"name":"blah",
     "this_must_go":"obsolette",
     "this_must_also_go":"unfixable",
     "type":4}
res = {k: x[k] for k in x if k not in ["this_must_go", "this_must_also_go"]}
print(res)

or this:

x = {"name":"blah",
     "this_must_go":"obsolette",
     "this_must_also_go":"unfixable",
     "type":4}
[x.pop(k) for k in ["this_must_go", "this_must_also_go"]]
print(x)

Output:

{'name': 'blah', 'type': 4}
Answered By: perpetualstudent
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.