coins = [
{'coin': "A", 'value': 2},
{'coin': "B", 'value': 5},
{'coin': "A", 'value': 1},
{'coin': "A", 'value': 3},
]
new = {}
for c in coins:
coin_name = c.get("coin")
coin_value = c.get("value", 0)
new[coin_name] = new.get(coin_name, 0) + coin_value
coin = []
for key in new:
coin.append({'coin': key, 'value': new[key]})
print(coin)
Результат:
[{'coin': 'A', 'value': 6}, {'coin': 'B', 'value': 5}]
Изменить: (добавлено значение bip_)
coins = [
{'coin': "A", 'value': 2, 'bip_value': 1},
{'coin': "B", 'value': 5, 'bip_value': 2},
{'coin': "A", 'value': 1, 'bip_value': 3},
{'coin': "A", 'value': 3, 'bip_value': 4},
]
new = {
'coin': {},
'bip': {}
}
for c in coins:
coin_name = c.get("coin")
coin_value = c.get("value", 0)
bip_value = c.get("bip_value", 0)
new['coin'][coin_name] = new['coin'].get(coin_name, 0) + coin_value
new['bip'][coin_name] = new['bip'].get(coin_name, 0) + bip_value
coin = []
for key in new['coin']:
coin.append({'coin': key, 'value': new['coin'][key], 'bip_value': new['bip'][key]})
print(coin)
Результат:
[{'coin': 'A', 'value': 6, 'bip_value': 8}, {'coin': 'B', 'value': 5, 'bip_value': 2}]