python - Merge values of same key, in list of dicts -


i relatively new python 2.7, , can't figure out following despite searching extensively on stackoverflow:

i have list of dicts wan't combine, when key same, , add specific values (in example 'price').

input:

[{'id1': 'a', 'price': '2', 'color': 'green'}, {'id1': 'b', 'price': '5', 'color': 'red'}, {'id1': 'a', 'price': '2', 'color': 'green'}]  

expected:

[{'id1': 'a', 'price': '4', 'color': 'green'}, {'id1': 'b', 'price': '5', 'color': 'red'}] 

same idea question before edit.

>>> data = [{'id1': 'a', 'price': '2', 'color': 'green'}, ...         {'id1': 'b', 'price': '5', 'color': 'red'}, ...         {'id1': 'a', 'price': '2', 'color': 'green'}] 

construct temporary dictionary , accumulate values in it

>>> temp = {} >>> d in data: ...     if d['id1'] not in temp: ...         temp[d['id1']] = {} ...     temp_d = temp[d['id1']] ...     temp_d['price'] = temp_d.get('price', 0) + int(d['price']) ...     temp_d.setdefault('colors', set()).add(d['color']) ...  >>> temp {'a': {'colors': {'green'}, 'price': 4}, 'b': {'colors': {'red'}, 'price': 5}} 

then using list comprehension , dictionary comprehension, reconstruct list of dictionaries.

>>> [{'id1': k, 'price': v['price'], 'colors': v['colors']} k, v in temp.items()] [{'id1': 'a', 'colors': {'green'}, 'price': 4}, {'id1': 'b', 'colors': {'red'}, 'price': 5}] 

>>> data = [{'id1': 'a', 'price': '2'}, {'id1': 'b', 'price': '5'}, ...         {'id1': 'a', 'price': '2'}] 

create temporary dictionary can accummulate sum of prices against ids,

>>> temp = {} >>> d in data: ...     temp[d['id1']] = temp.get(d['id1'], 0) + int(d['price']) ...  >>> temp {'a': 4, 'b': 5} 

here try value of d['id1'] temp , if not found, 0 returned. add price current dictionary , store result in temp against current id1.

then reconstruct list of dictionaries, list comprehension , dictionary comprehension, this

>>> [{'id1': k, 'price': temp[k]} k in temp] [{'price': 4, 'id1': 'a'}, {'price': 5, 'id1': 'b'}] 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -