I need to keep track of occurrences of items in parsed files in a structure as follows:
data= {'tomate': {'John': 2, 'mike': 2},
'pasta': {'mike': 1},
'wine': {'mike': 1, 'alex': 2}}
the dictionary starts as empty one. data = {} and its is being populated with values when they are not there and adding up users +1 if the user is there or =1 if the user is not yet there.
This is my code:
def modify(data, key, client):
try:
# if both keys are there
data[key][client] = data[key][client] +1
#print(f"{key} is there. {client} is there.")
except:
try:
data[key][client] = 1
#print(f"{client} not there, but {key}")
except:
data[key]={}
data[key][client] = 1
#print(f"{client} and {key} added")
return data
It works:
key="wine"
client = "alex"
modify(d, key, client)
giving:
{'tomate': {'John': 2, 'mike': 2},
'pasta': {'mike': 1},
'wine': {'mike': 1, 'alex': 3}}
The question is if using try/except is not the way to go, i.e. not pythonic, because I am relying on exceptions for the code to work properly which I feel is a little bit weird and might make the whole code much slower.
Is there any other option to keep track of a counter like this that I might have a look to that might be faster? Performance is very important of course since I have to count hundreds of millions of times.
EDIT 1: Evaluating the speed of a proposed solution I have this comparison that strikes me since my solution is faster (and I would not expect that):
EDIT 2: This question has been closed despite of very well elaborated answers and being directed to finding a proper way to solve a problem. It is really annoying that people just close questions like this. How can someone say that this questions is opinion-based if we are talking about computing times?