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)
new_dict[branch]= {'value': value, 'count': 0}dictis not ordered sequence, there is no append.new_dictis a list. Change[]to{}and it will be declared as an empty dictionary. Better yet, usedict().