Home > database >  How to assign a value to a dictionary if I need to reference it in the right hand side?
How to assign a value to a dictionary if I need to reference it in the right hand side?

Time:06-22

Here is the code that is giving me a KeyError. I understand why it's doing it but I am blank at how to solve it:

mydict = {}

range_val = [str(i).zfill(2) for i in range(100)]

for v in range_val:
   mydict[v] = mydict[v]   1  # Should create key if doesnt exist yet and value be 1
                              # Should update key if already exists and update value to  1

I get the data from reading a bunch of files and doing some processing to get the information I need. That information is held on another dictionary that I then use to try to do that. That is, instead of range_val like in the example I have somedict.values().

CodePudding user response:

defaultdict was designed for this.

import collections
mydict = collections.defaultdict(str)

range_val = [str(i).zfill(2) for i in range(100)]

for v in range_val:
   mydict[v] = mydict[v]   1

CodePudding user response:

If you just want to count how many occurrences of each item are in your iterable, you want collections.Counter.

from collections import Counter


my_dict = Counter(range_val)
  • Related