1

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

Community
  • 1
  • 1
guneysus
  • 6,203
  • 2
  • 45
  • 47
  • 1
    I have a doubt, Is approach 1 not functional ? – Vikash Singh Jan 03 '17 at 18:44
  • 1
    Very similar to your second way: Define `del del_id(d): del ['_id']` and then use `map` `map(del_id, iterable)` – Patrick Haugh Jan 03 '17 at 18:44
  • 1
    [Functional programming](https://en.wikipedia.org/wiki/Functional_programming) is a specific programming style that, among other things, tries to copy things, not delete them. But you also say you " just want to delete _id key from each element". Do you want to modify the original dicts? Then #2 is the normal python way to do it. Calling `filter` for this is frowned upon because you are depending on its side effects, not the return value of filter. – tdelaney Jan 03 '17 at 18:56

2 Answers2

5

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...

nosklo
  • 217,122
  • 57
  • 293
  • 297
1

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])