Week 359 – July 13th to July 19th

I’m pretty happy with how my week went on KA, although it was only as productive as my past few weeks (i.e. not really that productive… 🫤). I essentially only made it through one Lesson, getting through a handful of videos and articles, plus an exercise and a challenge. However, the reason why I’m somewhat pleased with how the week went is because I actually put in a better effort this week and I started to feel like I could read and understand code much easier. I know I’m still far away from being able to write Python code as well as I eventually want to be able to, but I definitely felt noticeable difference in my confidence and competence this week compared to previous weeks. I’m still spending a few hours each week reading Automate the Boring Stuff with Python and watching a YouTube series about Python for beginners by a creator called Dave Gray. At the end of Dave’s videos, his outro says, “a little progress every day will go a long way” which resonates deeply with me considering that’s how I learned math. So, all in all it was a good week even though I still wish I would have got more done. 🤷🏻‍♂️  

At the end of my last post, I mentioned that I ended the week completing the challenge from Lesson 2 and I was thinking of doing the bonus Step at the start of this week before moving on to Lesson 3. But when I looked at it, it wasn’t very clear and I didn’t want to spend time reacquainting myself with each module and function of the program, so I decided to just jump straight into the next Lesson to get the week going quickly.

Here’s everything I made notes on this week:

Unit 6 – Analyzing Data with Dictionaries

Lesson 3 – Nested Data: Dictionaries

Video – Data Modeling and APIs

I this video, Kim explained that when dictionaries get too big, you can create what I think of as sub-dictionaries, i.e. placing dictionaries IN a dictionary as key-value pairs. (It’s the same thing as putting sub-folders inside of folders on your desktop.) You can see the syntax for how this is done in the first screenshot above. Having sub-dictionaries inside of dictionaries seems very intuitive to me, and I find the organization of it very satisfying. A dictionary with sub-dictionaries is called a data structure and the act of figuring out how to structure the dictionary is called data modelling.

In the second screenshot above, Kim was saying that, upon request, data structures are passed from the backend to the frontend for the user using an API and most often using the language JSON.

Video – Accessing Nested Data

Kim explained in this video that putting dictionaries inside other dictionaries is called “nested data”.

This screenshot shows how to tell what data type is associated with what key based on the first character or bracket after the colon. If it’s a “ [ ” then it’s a list and if it’s a “ { ” then it’s a dictionary.

The two screenshots above show how you access data in a nested dictionary. The first of the two screenshots shows how to access a value in a nested dictionary by going one step at a time, and the second screenshot shows how to do it in one fell swoop.

This last screenshot shows an example of indexing into a dictionary -> list -> dictionary -> string by going gas_works -> reviews -> author -> rina.

Articles – Nested Data Patterns

This article went through three examples of data structures you might see using dictionaries.

In this example you can see how the keys are set to the tracking numbers and then pertinent info is added to the dictionary value associated with each tracking number.

I find this program/script a little hard to follow, but the get_latest function goes into the dictionary “packages” and returns “Out for delivery” as return is set to package[“scan_events”][–1] and the key “scan_events” is a list and [–1] gets the last elements of the list. (I don’t understand what “if not package [“scan_events”]: return “Unknown” does…)

Also, I stared at the has_error function for about 10 minutes before figuring it out. I don’t think I can articulate how it works, but I eventually realized that because “Departed origin facility” is in package[scan_events] twice, it triggers the return value to be True which end up printing “Package was double scanned”. 

This example was much easier for me to follow than the previous one. You can see that in the first key-value pair the value is a string, in the second key-value pair the value is an integer, and in the third and fourth key-value pairs the values, “sender” and “receptionist” respectively, are both dictionaries. It took me a second to decipher what all the first level keys were (not sure if that’s how to say it — I mean the first level of indentation), but then I realized I could look at the level of indentation to figure it out. Other than that, it’s pretty straightforward seeing how the {name} and {city} strings get called.

Exercise – Trace Nested Data: Dictionaries

Question 1

Question 2

This exercise was quite straightforward. I answered each question in less than a minute, but it did take me a second to think through the syntax in some of the questions. Even though it was fairly simple, this exercise was still helpful, giving me a chance to practice looking at this new kind of dictionary syntax. It helped me get a better handle on reading dictionaries themselves and understanding the methods/functions they were calling.

Challenge: Ad Exchange

As you can see from the instructions on the left side of the screenshot above, for Step 1 I had to compare the country of the user with the target_country in the ad_criteria.py module (both of which were dictionaries containing nested dictionaries, lists, and items). I initially tried writing:

def matches_location(user, ad):

    “””Returns True if user’s location matches the ad’s target countries.”””

    if user[“location”][“country”] == ad[“target_countries”]:

        return True

    else:

        return False

But that didn’t work. I copied everything into Gemini and it helped me come up with:

def matches_location(user, ad):

    “””Returns True if user’s location matches the ad’s target countries.”””

    # If there are no indicated target countries, return True

    if len(ad[“target_countries”]) == 0:

        return True

    # Otherwise, check to see if the user’s country is in target countries

    elif user[“location”][“country”] in ad[“target_countries”]:

        return True

    # If neither condition is True, then they don’t match

    else:

        return False

I keep forgetting to use the len(some_list) == 0 equation to check if a list is empty. The other mistake I made was thinking I needed to use the == sign between user[location][country] and as[target_country], but really I needed to use the “in” operator.

For this Step, I initially wrote:

def matches_interests(user, ad):

    “””Returns True if user’s interests match the ad’s target interests.”””

    if len(ad[“target_interests”]) == 0:

        return True

    elif user[“interests”][:] in ad[“target_interests”][:]:

        return True

    else:

        return False

But should have written:

def matches_interests(user, ad):

    “””Returns True if user’s interests match the ad’s target interests.”””

    if len(ad[“target_interests”]) == 0:

        return True

    for interest in user[“interests”]:

        if interest in ad[“target_interests”]:

            return True

    else:

        return False

When I looked at the instructions, my gut told me I needed to use a for loop, but I wasn’t sure how to do it. I got Gemini’s help and was disappointed that I didn’t figure it out on my own, but was happy that I at least had the correct intuition.

I sadly also needed to get Gemini’s help with this Step. It’s hard to explain, but the user’s purchases was a list of dictionaries for each purchase that included things like “category”, “date”, etc. So, I had to loop through the list of dictionaries pulling out the “category” value for each purchase dictionary (which you can see on lines 45 and 47) and compare it to what was in the target_purchase_categores list. I eventually figured it out but obviously needed to get Gemini’s help. 😮‍💨

Lesson 4 – Nested Data: Lists

Article – Data Records

This article began by giving the definitions of a Data Record and a Dataset:

This was the first example program in the article. Below the function, I copied four examples of the nested dictionaries in weather.py. The function itself prints each individual dictionary, the date, and a —– line for each nested dictionary. I didn’t know you could access a value in a nested dictionary with notation like print(forecast[“date”]) so I was happy to learn that.

In this example, you can see the function get_total_rainfall accesses the dictionary year with get_total_rainfall(weather.year) on line 12. It then accesses each nested dictionary with “for forecast in forecasts” and pulls the integer value for “precip” adding it to total rainfall.

This function, find_days_by_tamp, works similarly to get_total_rainfall in how it accesses the key-value pairs in each nested dictionary, but it checks to see if the value for “temp” in each day’s forecast (i.e. the nested dictionaries) is greater than 32 (the threshold) — side note: shouldn’t the word forecast in this context actually be ‘back’-cast? 🤔 —  then it adds the first four digits from the string value in the key “date” and returns the list of days.

This final example shows how you can iterate through all the year’s nested dictionaries and create a new dictionary, days, the contains the count for each of the five different conditions (cloudy, light rain, rain, sunny, and partly cloudy). It starts by creating an empty dictionary, days, then iterates though all the forecasts back-casts pulling each condition value from each individual back-cast and adding it to the days dictionary as a key if it’s not there AND incrementing the value of it by one. It does this using the code on line 8, “days[condition] = days.get(condition, 0) + 1”, which I sort of understand but not really. 😔 After that, the two variables sunny_days and rainy_days pull the sunny days and rainy days values from the days dictionary which are used in the two print statements.

And that was it for this week. Like I said, it could have been more productive but it also could have been a lot worse. And in the big picture, I feel like I’m actually making progress learning and understanding Python which is really what matters, so I’ve got that going for me which is nice. This coming week, I’m hoping to get through more material on KA than I did this past week, but even if I have a similar week as this one, I would be happy with it. Nonetheless! — fingers crossed, as always, that I can get a lot of work done this week so I can become and AMAZING coder sooner rather than later! 🤞🏼

Leave a Reply

Your email address will not be published. Required fields are marked *