0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Das Raf
  • 55
  • 6
  • 2
    Can you modify the dictionaries in place, or do you need to return a new list of new dictionaries? – Barmar Jan 13 '23 at 01:00
  • It's easier if you know the fields you want to keep. – Barmar Jan 13 '23 at 01:00
  • 3
    If you want to modify the dicts in-place, [don't use a list comprehension, because it would only be for side effects](/a/5753614/4518341); just use a plain for-loop. Then see [How can I remove a key from a Python dictionary?](/q/11277432/4518341) as well as [How do I delete items from a dictionary while iterating over it?](/q/5384914/4518341) – wjandrea Jan 13 '23 at 01:02
  • it doesnt matter if the dictionary is changed because this list is on its final stage before shipped out as json response, so something like json.dumps(the_list_without_unwanted_fields) – Das Raf Jan 13 '23 at 01:14

3 Answers3

2

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]
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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
]
Hanwei Tang
  • 413
  • 3
  • 10
1

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'}
]
Mark
  • 90,562
  • 7
  • 108
  • 148