-1

I am trying to create a dictionary in which i have to keep incrementing a value

So i am trying the following:

from collections import defaultdict
test = defaultdict(dict)
for item in debitlist:
    if not something:
        test[item['name']]['count'] += 1
        test[item['name']]['amount'] += item['name']['amount']

I am trying to get a dictionary like

{ "Krishna" : { "count" : totalcount, "amount" : totalamount } }

I am getting Keyerror for count. How to resolve this and get what i want

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

0

You need the internal dictionary to also be a defaultdict but with a default of int or float.

Make a function to create a defaultdict with a number as default, e.g:

from collections import defaultdict

def floatdict():
    return defaultdict(float)

Then you can use it in place of the vanilla dict you were previously using:

test = defaultdict(floatdict)

Then:

test['Krishna']['count'] += 1
test['Krishna']['amount'] += 10

You can convert the defaultdict back to a dict and print it:

print(dict(test['Krishna']))

Output:

{'amount': 10.0, 'count': 1.0}
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • what is the need of function. cant we define test = defaultdict(float) – Santhosh Aug 21 '19 at 10:46
  • I tried and says `TypeError: 'float' object is not subscriptable` – Santhosh Aug 21 '19 at 10:47
  • `test` would be a dictionary of `float` values. You want a dictionary of dictionaries of float values. – Peter Wood Aug 21 '19 at 10:47
  • It looks like you haven't done exactly what I suggested. Are you sure you're using it `defaultdict(floatdict)`? – Peter Wood Aug 21 '19 at 10:50
  • Can i have mixed items i.e count as int, amount as float, branch as str – Santhosh Aug 21 '19 at 13:11
  • No. You could use dict.setdefault instead. That would allow you to set defaults per key. Read the docs and search for questions about it if you need to understand further. Would link for you to save your effort but am on mobile so difficult. – Peter Wood Aug 21 '19 at 23:03