Return dictionary with one changed item

Let's say I have a list of dictionaries:

>>> d = [{'a': 2, 'b': 3, 'c': 4}, {'a': 5, 'b': 6, 'c': 7}]

And I want to perform a map operation in which I change only one value in each dictionary. One possible way to do this is to create a new dictionary that simply contains the original values ​​along with the changed ones:

>>> map(lambda x: {'a': x['a'], 'b': x['b'] + 1, 'c': x['c']}, d)
[{'a': 2, 'c': 4, 'b': 4}, {'a': 5, 'c': 7, 'b': 7}]

This can become unshakable if dictionaries have many elements.

Another way could be to define a function that copies the original dictionary and changes only the necessary values:

>>> def change_b(x):
...     new_x = x.copy()
...     new_x['b'] = x['b'] + 1
...     return new_x
...
>>> map(change_b, d)
[{'a': 2, 'c': 4, 'b': 4}, {'a': 5, 'c': 7, 'b': 7}]

This, however, requires a separate function to be written and loses the elegance of the lambda expression.

Is there a better way?

+4
source share
3 answers

This works (and compatible with python2 and python3 1 ):

>>> map(lambda x: dict(x, b=x['b']+1), d)
[{'a': 2, 'c': 4, 'b': 4}, {'a': 5, 'c': 7, 'b': 7}]

, , lambda , lambda... , - - lambda , , , . lambda, , , , , ...

1 map python3.x, ...

+4

-, . , Python 3.5 PEP 448:

>>> d = [{'a': 2, 'b': 3, 'c': 4}, {'a': 5, 'b': 6, 'c': 7}]
>>> d
[{'b': 3, 'a': 2, 'c': 4}, {'b': 6, 'a': 5, 'c': 7}]
>>> [{**x, 'b': x['b']+1} for x in d]
[{'b': 4, 'a': 2, 'c': 4}, {'b': 7, 'a': 5, 'c': 7}]

map, , 2, .: -)

+3

for update. :

dcts = [{'a': 2, 'b': 3, 'c': 4}, {'a': 5, 'b': 6, 'c': 7}]
dcts = [d.update({'b': d['b']+1}) or d for d in dcts]

: dicts:

from copy import copy
dcts = [d.update({'b': d['b']+1}) or d for d in map(copy, dcts)]
+1

All Articles