Introduction to Python Programming Course - Part 8

 Weekend entry - part 1! The current focus is control flow. I really got into for loops last time - lots to pick up on there. Let's go!

Start Time - 10:16

Building Dictionaries

So you can create a list, then iterate over each item to add to an empty dictionary, of the count. So if the word isn't already there, it sets to 1. Then adds one on if already there. Got it.

The other way is the 'get' method. 

First method practice - 

driver_winners_2022 = ["Leclerc", "Verstappen", "Leclerc", "Verstappen", "Verstappen", "Perez", "Verstappen", "Leclerc", "Verstappen", "Verstappen", "Sainz", "Verstappen", "Russell", "Verstappen"]


driver_winners_count = {}


for driver in driver_winners_2022:

    if driver not in driver_winners_count:

        driver_winners_count[driver] = 1

    else:

        driver_winners_count[driver] += 1

            

print(driver_winners_count)


Key bit here was alignment - that really demarcates hierarchy of code!

For method 2, it would be..


for driver in driver_winners_2022:

    driver_winners_count[driver] = driver_winners_count.get(driver, 0) + 1


With some practice both do make sense. It basically returns the driver as the key then the number as the value e.g. Leclerc: 3 etc.


Iterating in Dictionaries

So if you do the usual for in etc. then you would get the keys but not the values.   You need a specific code with items method.

Yes! Needed some help and actually ditched the else bit, as I was checking if it WAS in first for the fruit challenge. 

Final challenge - got it!

fruit_count, not_fruit_count = 0, 0

basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}

fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']


#Iterate through the dictionary

for item, number in basket_items.items():


#if the key is in the list of fruits, add to fruit_count.

    if item in fruits:

        fruit_count += number

#if the key is not in the list, then add to the not_fruit_count

    else:

        not_fruit_count += number


print(fruit_count, not_fruit_count)


Finish Time - 10:45 (approx 30 minutes)

Just a bit today.   Managed a good focused time on this one area. Next it will be while loops. This section definitely needs more time on it!

    

Comments