I have a function that is used repeatedly in a script, and I'm finding that it's taking approximately forever to run. I am wondering if there's something obvious that I can do to make it more efficient.
It takes 2 inputs:
First is fairly large list of dictionaries (up to around 1,000,000 items), with each dictionary containing two keys, like:
{'id': id_string, 'amount': amount_int}
The second input is a smaller list (50,000 to 100,000) of just strings of ids:
[id1, id2, id3... idn]
I want to find the sum of the 'amount' values in the big list of dictionaries if the 'id' key is present in the list of ids.
What I have now is:
So pretty straightforward. The problem is that it's taking what seems to be a very long time to do that calculation-- upwards of 10 minutes when the list of dictionaries is 750k records and the smaller list of ids is 75k records. When I have to do this 50+ times it means that the program takes many hours to complete.
Am I missing an obvious way to do this quickly? Or do I just need to accept that this is a very inefficient kind of calculation? There are some other areas in the code where I'm doing set intersections and those are super fast-- is there some way to essentially do that with the two lists and filter the dictionaries out that way?
Thanks in advance.
It takes 2 inputs:
First is fairly large list of dictionaries (up to around 1,000,000 items), with each dictionary containing two keys, like:
{'id': id_string, 'amount': amount_int}
The second input is a smaller list (50,000 to 100,000) of just strings of ids:
[id1, id2, id3... idn]
I want to find the sum of the 'amount' values in the big list of dictionaries if the 'id' key is present in the list of ids.
What I have now is:
Code:
def my_func(big_list, list_of_ids):
total = sum([d['amt'] for d in big_list if d['id'] in list_of_ids])
return total
So pretty straightforward. The problem is that it's taking what seems to be a very long time to do that calculation-- upwards of 10 minutes when the list of dictionaries is 750k records and the smaller list of ids is 75k records. When I have to do this 50+ times it means that the program takes many hours to complete.
Am I missing an obvious way to do this quickly? Or do I just need to accept that this is a very inefficient kind of calculation? There are some other areas in the code where I'm doing set intersections and those are super fast-- is there some way to essentially do that with the two lists and filter the dictionaries out that way?
Thanks in advance.