Search code examples
pythonlist-comprehension

handy way to get rid of some fields using list comprehension


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?


Solution

  • 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'}
    ]