Question: Elegant way to delete single key of from each element in iterable

Question

Elegant way to delete single key of from each element in iterable

Answers 2
Added at 2017-01-03 19:01
Tags
Question

Is it possible to manipulate each dictionary in iterable with lambdas?

To be clarify, just want to delete _id key from each element.

Wonder If there is an elegant way to achieve this simple task without 3rd parties like (toolz), functions, or copying dict objects.


Possible solutions that I do not search for.

  1. Traditional way:

    cleansed = {k:v for k,v in data.items() if k not in ['_id'] }
    
  2. Another way:

    def clean(iterable):
        for d in iterable:
            del d['_id']
        return
    
  3. 3rd Party way:

Python functional approach: remove key from dict using filter

Answers
nr: #1 dodano: 2017-01-03 19:01

Functional programming tendency is to not alter the original object, but to return a new modified copy of the data. Main problem is that del is a statement and can't be used functionally.

Maybe this pleases you:

[d.pop('_id') for d in my_dicts]

that will modify all the dictionaries in my_dicts in place and remove the '_id' key from them. The resulting list is a list of _id values, but the dictionaries are edited in the original my_dicts.

I don't recommend using this at all, since it is not as easy to understand as your second example. Using functional programming to alter persistent data is not elegant at all. But if you need to...

nr: #2 dodano: 2017-01-03 19:01

Check if this do what you want:

# Python 2.x
func = lambda iterable, key="_id": type(iterable)([{k: v for k, v in d.iteritems() if k != key} for d in iterable])

# Python 3.x
func = lambda iterable, key="_id": type(iterable)([{k: v for k, v in d.items() if k != key} for d in iterable])
Source Show
◀ Wstecz