1

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)
5
  • 1
    do as new_dict[branch]= {'value': value, 'count': 0} Commented Mar 31, 2015 at 16:01
  • In Python normal dict is not ordered sequence, there is no append. Commented Mar 31, 2015 at 16:02
  • new_dict is a list. Change [] to {} and it will be declared as an empty dictionary. Better yet, use dict(). Commented Mar 31, 2015 at 16:02
  • Grijesh, that was the answer I was looking for. Thanks. Commented Mar 31, 2015 at 16:16
  • Ken, I also took your suggestion and added new_dict = dict() Commented Mar 31, 2015 at 16:16

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.