Reputation: 25
I have the following dictionary:
my_dict = { 'order1': ['10','20','30'], 'order2': ['11','12','13'] }
I have this pandas dataframe:
SKU | Location |
---|---|
10 | 00-2 |
30 | 00-3 |
3 | 00-0 |
I want to loop through the dictionary, and check if the items in each order (for example order1 has 10, 20 and 30) are in the DF, and if they are, where is their location? Then, I want to add this new information to a dictionary like so:
new_dict = { 'order1': ['00-2','00-3'] }
This is the code:
col = df['SKU'].tolist()
col_str = [str(x) for x in col]
locs = []
for key, value in my_dict.items():
for i in range(len(value)):
if value[i] in col_str:
locs.append(df.loc[df['SKU'] == value[i],"Location"])
new_dict[key] = locs
else:
print("no")
I either get invalid type comparison, False or this error message when I remove the df['SKU'] == value[i]
to replace it with just the value:
KeyError: 'the label [10] is not in the [index]'
Upvotes: 1
Views: 57
Reputation: 10960
Create another mapping dictionary from the dataframe
sku_dict = dict(zip(df.SKU.astype(str), df.Location))
Then just get the key from this dictionary
{k: [sku_dict.get(item) for item in v if sku_dict.get(item)] for k, v in my_dict.items()}
Output
{'order1': ['00-2', '00-3'], 'order2': []}
Upvotes: 2
Reputation: 18406
You can apply lambda to get the dictionary key, then explode the order, and groupby order and call agg to form list of orders finaly to_dict() will give you the dictionary.
output=(df.assign(order=df['SKU']
.astype(str)
.apply(lambda x: [key for key in my_dict if x in my_dict[key]]))
.explode('order')
.groupby('order')['Location'].agg(list)
.to_dict()
)
# output
{'order1': ['00-2', '00-3']}
Upvotes: 1