Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop over a value in a dictionary using elements in a list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading