Same as your question before editing.
>>> data = [{'id1': 'a', 'price': '2', 'color': 'green'}, ... {'id1': 'b', 'price': '5', 'color': 'red'}, ... {'id1': 'a', 'price': '2', 'color': 'green'}]
Create a temporary dictionary and copy the values ββinto it
>>> temp = {} >>> for 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 and dictionary comprehension, restore the list of dictionaries.
>>> [{'id1': k, 'price': v['price'], 'colors': v['colors']} for 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 a temporary dictionary in which we can sum the sum of prices against their identifiers,
>>> temp = {} >>> for d in data: ... temp[d['id1']] = temp.get(d['id1'], 0) + int(d['price']) ... >>> temp {'a': 4, 'b': 5}
Here we try to get the value d['id1'] from temp , and if it is not found, 0 will be returned. Then we add price from the current dictionary and save the result back to temp against the current id1.
Then restore the list of dictionaries using list comprehension and dictionary comprehension, e.g.
>>> [{'id1': k, 'price': temp[k]} for k in temp] [{'price': 4, 'id1': 'a'}, {'price': 5, 'id1': 'b'}]