List comprehensions are usually faster than equivalent logic in for loops, you can find lots of discussions on this topic, these are just examples: Why list comprehension can be faster than map() in Python? and https://www.linkedin.com/pulse/list-comprehension-python-always-faster-than-alex-falkovskiy/.
So my first thought is to rewrite your logic as a list comprehension.
If I understood your code correctly, you want to update prices for items priced at 1.0 to what is the new category price for that item.
Item category is in the categories list, and new prices for categories is in the AllCats dict, which you are retrieving using AllCats[j][0]
where j
is category name.
Next, I will use numpy arrays to create a filter based on list price, np_filter = np_prices == 1.0
. Filter is then used in a list comprehension to retrieve updated price
np_prices[np_filter] = [allCats[c][0] for c in np_categories[np_filter]]
full code:
allCats = { 'a' : [7,2,3], 'b':[2,3,4]}
prices=[2,1.0,1.1,1.0,1.0]
categories = ['b','a','b','b','a']
import numpy as np
np_prices = np.array(prices)
np_categories = np.array(categories)
np_filter = np_prices == 1.0
np_prices[np_filter] = [allCats[c][0] for c in np_categories[np_filter]]
ofcourse you need to ensure that your allCats has entries for all values in categories so you dont get an out of bound error.