Reputation: 546
I am having trouble with the following code. I need to add a key to a python dictionary if it does not exist, and if it does then I need to add to the value. My output should look like this.
{'STA': {'value':-62**.***, 'count': 4}}.....
But I'm getting this instead.
{'STA': {'value': -1194.14562548, 'count': 0}},
{'STA': {'value': -5122.985396600001, 'count': 0}},
{'STA': {'value': 25.2293, 'count': 0}},
{'STA': {'value': 34.0099, 'count': 0}},
What am I doing wrong?
new_dict = []
for item in sales_orders['progress_output']:
ex = (list(filter(lambda ex:ex['_branch_shortname'].strip() == item['_branch_shortname'].strip(), expenses)))
value = float(item['gross_profit'].strip().replace(',', '')) - (float(item['load_factor_extended'].strip().replace(',', '')) * float(ex[0]['value']))
branch = item['_branch_shortname'].strip()
if branch in new_dict:
new_dict[branch]['value'] += value
new_dict[branch]['count'] += 1
else:
new_dict.append({branch: {'value': value, 'count': 0}})
#print(item['_branch_shortname'], value)
print(new_dict)
Upvotes: 1
Views: 179
Reputation: 30288
You can use setdefault to ensure there is a default value, setdefault
returns the value if it already exists for key (first parameter) or adds the default (second parameter) and returns it:
new_dict = {}
for ...:
b = new_dict.setdefault(branch, {'value': 0, 'count': 0})
b['value'] += value
b['count'] += 1
You can also use a defaultdict
:
from collections import defaultdict
new_dict = defaultdict(lambda: {'value': 0, 'count': 0})
for ...:
new_dict[branch]['value'] += value
new_dict[branch]['count'] += 1
Upvotes: 1