I would like to know if there is a more efficient way to append a dict value if the key exists, or create one if not. For the moment, I use a "if key in set(dict.keys())
"
I read many topics that talk about collections.defaultdict
but is it efficient ? I mean, when you use a collections.defaultdict
, does python make a "if key in ..." or does it work differently ?
My problem is that my dict is getting bigger and bigger, so my if key in set(dict.keys())
is getting longer to execute each time
Here is an example of what I talk about :
# a_list is a result of a loop that can iterate more than 10, 100, 1000...times
a_list = [[url1, sessions, transactions], [url2, sessions, transactions]...]
mydict = {}
for i in a_list:
# if my key doesn't exist
if i[0] not in set(mydict.keys()):
mydict[i[0]] = {}
mydict[i[0]]['session'] = i[1]
mydict[i[0]]['transactions'] = i[2]
else:
# if my key exists
mydict[i0]['sessions'] += i[1]
mydict[i0]['transactions'] += i[2]
To be more precise, this script is made to deal with Google Analytics API, to avoid Sampling (so I make requests for each day of a month, so there is big chances that my urls (mydict keys) are the same for each day I request.