Search code examples
pythonpython-3.xdictionarynested-loopsnested-lists

How to iterate through a list with nested dictionaries?


So i have a list with nested dictionaries inside them and what i want to do is read the values of views from the dictionaries and put them through a multiplier.

video_ads=({'title': 'Healthy Living', 'company': 'Health Promotion 
Board','views': 15934},
{'title': 'Get a ride, anytime anywhere', 'company': 'Uber', 'views': 
923834},
{'title': 'Send money with GrabPay', 'company': 'Grab', 'views': 23466},
{'title': 'Ubereats now delivers nationwide', 'company': 'Uber', 'views': 
1337},
{'title': 'Get cabs now with UberFlash', 'company': 'Uber', 'views': 90234})

so what i am trying to do is get the title together with the views mulitiplied by a certain factor, this is what i've written so far

def payment_for_views(x):
    for x in range(0,5):
        x = x+1

        if video_ads[x]['views'] >= 50000:
            payment = video_ads[x]['views']*0.55
        elif views <50000 and video_ads[x]['views'] >=10000:
            payment=video_ads[x]['views']*0.68
        else:
            payment = video_ads[x]['views']*0.82
    #print(x)
    print(video_ads[x]['title'] + ': $'+ str(payment))
    print(video_ads[x]['title'] + ': $'+ str(payment))
    print(video_ads[x]['title'] + ': $'+ str(payment))
    print(video_ads[x]['title'] + ': $'+ str(payment))
    print(video_ads[x]['title'] + ': $'+ str(payment))

But it seems to be printing only one line for example:

 Get cabs now with UberFlash: $49628.700000000004
 Get cabs now with UberFlash: $49628.700000000004
 Get cabs now with UberFlash: $49628.700000000004
 Get cabs now with UberFlash: $49628.700000000004
 Get cabs now with UberFlash: $49628.700000000004

that is all i get. I need 5 lines all of them with the various titles and various amounts. Help!!! and thanks in advance!


Solution

  • You need to place your print statement within your for loop.

    Leaving print after and outside your loop means that x will be fixed at the final value set in the for loop.

    def payment_for_views(x):
        for x in range(len(x)):
            if video_ads[x]['views'] >= 50000:
                payment = video_ads[x]['views']*0.55
            elif video_ads[x]['views'] <50000 and video_ads[x]['views'] >=10000:
                payment=video_ads[x]['views']*0.68
            else:
                payment = video_ads[x]['views']*0.82
            print(video_ads[x]['title'] + ': $'+ str(payment))
    

    There are a number of ways you can improve your code:

    1. Iterate your dictionaries directly rather than by index.
    2. Extract the "views" value once for each dictionary and assign to a variable.
    3. Use chained comparisons for checking whether a value is between two others.
    4. Use f-strings (Python 3.6+) with decimal precision specified.

    Here's a demo:

    def payment_for_views(x):
        for item in x:
            views = item['views']
            if views >= 50000:
                factor = 0.55
            elif 10000 <= views < 50000:
                factor = 0.68
            else:
                factor = 0.82
    
            print(f'{item["title"]}: ${views*factor:.2f}')
    
    payment_for_views(video_ads)
    

    Result:

    Healthy Living: $10835.12
    Get a ride, anytime anywhere: $508108.70
    Send money with GrabPay: $15956.88
    Ubereats now delivers nationwide: $1096.34
    Get cabs now with UberFlash: $49628.70