Home > Net >  How to loop over a value in a dictionary using elements in a list
How to loop over a value in a dictionary using elements in a list

Time:12-29

I have a list (let's say A) which has different visitor ids as its item

A=[1234,4650,8609,1675]

I have a dictionary which has the following key-value pairs

data = {"visitorid": "1234", "placement": "recommendations-ctr-airp"} 

I run a predict retail API on the dictionary which will give product recommendations for the visitorID=1234.

The chain of code is as below:

from unittest.mock import Mock
data = {"visitorid": "1234", "placement": "recommendations-ctr-airp"}
req = Mock(get_json=Mock(return_value=data), args=data)
df = recommend(req)

The dataframe 'df' will be a combination of visitor Id and all the products recommended by the retail API for that particular visitor ID :

visitorId ProductID
1234 AA
1234 AB

The problem that I'm facing is that how do I use list A to run the above chain of code to get the output for all the visitor ids?

CodePudding user response:

If you want to execute code for every element in a list, a simple for loop should work.

Example:

A = [1234,4650,8609,1675]
list_of_dfs = []

for v_id in A:
    data = {"visitorid": str(v_id), "placement": "recommendations-ctr-airp"}
    req = Mock(get_json=Mock(return_value=data), args=data)
    df = recommend(req)
    list_of_dfs.append(df)

Then you have a list of the dataframes in list_of_dfs

  • Related