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

Having trouble iterating over a JSON response

Iterating over the JSON response below is creating the same duplicate results in the list I am appending to, rather than iterating over each dict and appending each unique value.

I am not sure what I am doing wrong.

results_dict = [{'keywordText': 'fake toddler makeup', 'matchType': 'broad'}, {'keywordText': 'kid makeup kit girl', 'matchType': 'broad'}, {'keywordText': 'toddler makeup', 'matchType': 'broad'}]
asins = ['B087CRJ6KZ', 'B08QVDGPG4']
results = {}
suggested_kws = []

for asin in asins:
    for kw in results_dict:
        kw = results_dict[0]['keywordText']
        suggested_kws.append(kw)
        
    results[asin] = suggested_kws

print(results)

current result:

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

{'B087CRJ6KZ': ['fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup'],
'B08QVDGPG4': ['fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup', 'fake toddler makeup']}

expected result:

{'B087CRJ6KZ': ['fake toddler makeup', 'kid makeup kit girl', 'toddler makeup'], 
'B08QVDGPG4': ['fake toddler makeup', 'kid makeup kit girl', 'toddler makeup']}

>Solution :

You can use a dict-comprehension here.

results_dict = [{'keywordText': 'fake toddler makeup', 'matchType': 'broad'}, {'keywordText': 'kid makeup kit girl', 'matchType': 'broad'}, {'keywordText': 'toddler makeup', 'matchType': 'broad'}]
asins = ['B087CRJ6KZ', 'B08QVDGPG4']

results = {a: [x['keywordText'] for x in results_dict] for a in asins}
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