This notebook provides practice problems associated with lesson 2. It is divided into several parts:

  • Part 1 - most approachable place to start. Practices syntax and concepts

  • Part 2 - a step up from part 1. Integrates concepts from accross the lesson in more applied scenarios

Lists and Dictionaries Answers#

Part 1#

Lists#

  1. Create a list with 4-6 items that represents some foods.

pastries = ['bagels', 'baklava', 'croissant', 'msemen']
  1. Write a line of code to figure out how many foods are in your list. Write a print statement which displays Number of foods is: ___ where the __ space is calculated based on the number of items in your list.

pastries = ['bagels', 'baklava', 'croissant', 'msemen']
print('Number of foods is: ', len(pastries))
Number of foods is:  4
  1. 🐞 Debugging: Find and fix the error in the following block of code.

# Two problems:
# 1) Double quotation after co
# 2) No comma after co
pollutants = ['co" 'co2', 'no2', 'o3']
  Cell In[3], line 4
    pollutants = ['co" 'co2', 'no2', 'o3']
                                        ^
SyntaxError: unterminated string literal (detected at line 4)
# Working version
pollutants = ['co', 'co2', 'no2', 'o3']

Indexing#

  1. For each of the bullets print out the colors from the colors list using indices.

  • red

  • blue, yellow, white (together)

colors = ['red', 'green', 'blue', 'yellow', 'white', 'black']
colors[0]
'red'
colors[2:5]
['blue', 'yellow', 'white']
  1. 🐞 Debugging: The goal of the following block of code is to print out the value o3. Find and fix the error.

# Problem: there is no value at index 4.  The last item in this list is at index 3.
pollutants = ['co', 'co2', 'no2', 'o3']
print(pollutants[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-14-1bec3e92d526> in <module>
      1 # Problem: there is no value at index 4.  The last item in this list is at index 3.
      2 pollutants = ['co', 'co2', 'no2', 'o3']
----> 3 print(pollutants[4])

IndexError: list index out of range
# Correct version
pollutants[3]

Functions/Methods#

  1. Returning to our list of pollutants, let’s say we learned that no2 is the wrong value. Instead we want that item to be nox. Update the pollutants list below so the output is ['co', 'co2', 'nox', 'o3'].

pollutants = ['co', 'co2', 'no2', 'o3']
pollutants[2] = 'nox'
pollutants
['co', 'co2', 'nox', 'o3']
  1. This article linked in the lecture describes a few common list methods. Scroll down to where the article talks about pop() and apply that to our pollutants list by removing ‘co’ from the list.

# Sorting forward
pollutants.pop(0)
print(pollutants)
['co2', 'nox', 'o3']

Dictionaries#

  1. Create a dictionary that has an item for each of the last 4 days and displays the weather condition on each of those days.

weather_conditions = {
    'monday': 'sunny',
    'sunday': 'partly cloudy',
    'saturday': 'tornado',
    'friday': 'sunny'
}
  1. Using the dictionary you made in the previous question:

  • print all the keys

  • print all the values

  • pick one specific key and print its value

weather_conditions.keys()
dict_keys(['monday', 'sunday', 'saturday', 'friday'])
weather_conditions.values()
dict_values(['sunny', 'partly cloudy', 'tornado', 'sunny'])
weather_conditions['friday']
'sunny'
  1. 🐞 Debugging: Find and fix the error in the following block of code.

# Problem: missing a comma after the 5 in the 'quality_flag' item
metadata = {
    'location': 'Nairobi', 
    'quality_flag': 5
    'zenith': 60, 
    'clouds': True,
    'data_center': ['LPDAAC', 'ASDC'],
}
  File "<ipython-input-24-a4eb952b1e43>", line 5
    'zenith': 60,
    ^
SyntaxError: invalid syntax
# Working version
metadata = {
    'location': 'Nairobi', 
    'quality_flag': 5,
    'zenith': 60, 
    'clouds': True,
    'data_center': ['LPDAAC', 'ASDC'],
}
  1. 🐞 Debugging: The goal of the following block of code is to print out the keys of the dictionary metadata. Find and fix the error.

metadata = {
    'location': 'Nairobi', 
    'quality_flag': 5,
    'zenith': 60, 
    'clouds': True,
    'data_center': ['LPDAAC', 'ASDC'],
}
# Problem: missing the () in the syntax for `.keys()`
print(metadata.keys)
<built-in method keys of dict object at 0x000001E692C202C0>
# Working version
print(metadata.keys())
dict_keys(['location', 'quality_flag', 'zenith', 'clouds', 'data_center'])

Adding or changing items#

  1. Using the following dictionary change the value for state to PA.

census_block7 = {
    'state': 'NY',
    'block_groups': ['01', '02', '03', '04'],
    'median_education': 'some_bachelors',
    'total_housing_units': 9329432,
}
census_block7['state']  = 'PA'
  1. Using the census_block7 dictionary add the value 78.2 for a new item called employment_rate.

census_block7['employment_rate'] = 78.2

Data Structures#

Come up with 1-2 fake datasets that make sense as a list and type out an example list. Do the same for 1-2 dictionaries.

# Example
max_daily_temperatures_NYC = [56, 50, 49, 49, 60]
# List dataset
passenger_totals = [923, 837, 283, 295]
# Dictionary dataset
weather_sunday = {
    'conditions': 'thunderstorms',
    'high_temp': 67,
    'low_temp': 50,
    'humidity': 90,
}

Part 2#

Assign the value of a dictionary to another variable

Question 1#

The list below represents the smallest size of particulate matter (PM) measured in a series of air samples. Find the number of occurances of PM2.5 and PM10 in the list. (One of the methods from the list methods article could be a good place to start).

pm_levels = ['PM1', 'PM2.5', 'PM1', 'PM10', 'PM10', 'PM10', 'PM2.5', 'PM10', 'PM1', 'PM2.5']
# Number of occurances of 'PM2.5'
pm_levels.count('PM2.5')
3
# Number of occurances of 'PM10'
pm_levels.count('PM10')
4

Question 2#

One very common practice in dictionaries is called nesting. Nesting is the practice of putting one data structure inside of another data structure. So a nested dictionary is a dictionary inside of another dictionary.

state_info = {
    'state': 'AK',
    'motto': 'north to the future',
    'num_of_counties': 29,
    'population': {
        'ages_0_25': 28393,
        'ages_25_50': 25920,
        'ages_over_50': 8943,
        }
}

A) Print out the following pieces of information from the dictionary above:

  • the motto

  • the population ages 25 to 50

state_info['motto']
'north to the future'
state_info['population']['ages_25_50']
25920

B) Change the population ages 0 to 25 to 98988

state_info['population']['ages_25_50'] = 98988

C) Add a new age bracket to the population dictionary by adding an additional item: ages_50_75 with the population 3333. Change the item ages_over_50 to be renamed ages_50_75.

I accidently typed an error into this question. I mistyped the new variable, which made the variable name repetitive.

Part C should state:

Add a new age bracket to the population dictionary by adding an additional item: ages_over_75 with the population 3333. Change the item ages_over_50 to be renamed ages_50_75.

# Rename the the key `ages_50_75` -- in two steps
# Remove the old value
state_info['population'].pop('ages_over_50')
# Replace the value with a new name
state_info['population']['ages_50_75'] = 8943

OR

# Rename the the key `ages_50_75` -- in one step
state_info['population']['ages_50_75'] = state_info['population'].pop('ages_over_50')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-41-fcc5141fb57b> in <module>
      1 # Rename the the key `ages_50_75` -- in one step
----> 2 state_info['population']['ages_50_75'] = state_info['population'].pop('ages_over_50')

KeyError: 'ages_over_50'

Step 2: Add the new key

state_info['population']['ages_over_75'] = 3333
state_info
{'state': 'AK',
 'motto': 'north to the future',
 'num_of_counties': 29,
 'population': {'ages_0_25': 28393,
  'ages_25_50': 98988,
  'ages_50_75': 8943,
  'ages_over_75': 3333}}

Question 3#

Another common example of nested objects is a list of dictionaries. Below we have the same nested dictionary as in question two, but we have a list of three states’ data.

census_by_state = [
    {
        'state': 'AK',
        'motto': 'north to the future',
        'num_of_counties': 29,
        'population': {
            'ages_0_25': 28393,
            'ages_25_50': 25920,
            'ages_over_50': 8943,
            }
    },
    {
        'state': 'FL',
        'motto': 'in god we trust',
        'num_of_counties': 67,
        'population': {
            'ages_0_25': 382933,
            'ages_25_50': 483923,
            'ages_over_50': 938923,
            },
    },
    {
        'state': 'MN',
        'motto': 'letoile du nord',
        'num_of_counties': 87,
        'population': {
            'ages_0_25': 39323,
            'ages_25_50': 109282,
            'ages_over_50': 92837,
        },
    },
]

A) Print the following population numbers:

  • population ages 25-50 in Alaska

  • number of counties in Florida

  • population ages 0-25 in Minnesota

  • motto of alaska

census_by_state[0]['population']['ages_25_50']
25920
census_by_state[1]['num_of_counties']
67
census_by_state[2]['population']['ages_0_25']
39323
census_by_state[0]['motto']
'north to the future'

B) Change:

  • the population over age 50 in florida to 8898

  • the motto of minnesota to “go pack go!”

  • the number of counties in alaska to 31

census_by_state[1]['population']['ages_over_50'] = 8898
census_by_state[2]['motto'] = 'Go pack go!'
census_by_state[0]['num_of_counties'] = 31
census_by_state
[{'state': 'AK',
  'motto': 'north to the future',
  'num_of_counties': 31,
  'population': {'ages_0_25': 28393,
   'ages_25_50': 25920,
   'ages_over_50': 8943}},
 {'state': 'FL',
  'motto': 'in god we trust',
  'num_of_counties': 67,
  'population': {'ages_0_25': 382933,
   'ages_25_50': 483923,
   'ages_over_50': 8898}},
 {'state': 'MN',
  'motto': 'Go pack go!',
  'num_of_counties': 87,
  'population': {'ages_0_25': 39323,
   'ages_25_50': 109282,
   'ages_over_50': 92837}}]

C) Add a new state to the list of dictionaries. Pick whatever state and values you want.

census_by_state.append(
{
    'state': 'NV',
    'motto': 'all for our country',
    'num_of_counties': 16,
    'population': {
        'ages_0_25': 1923,
        'ages_25_50': 75832,
        'ages_over_50': 32743
    }
}
)
census_by_state
[{'state': 'AK',
  'motto': 'north to the future',
  'num_of_counties': 31,
  'population': {'ages_0_25': 28393,
   'ages_25_50': 25920,
   'ages_over_50': 8943}},
 {'state': 'FL',
  'motto': 'in god we trust',
  'num_of_counties': 67,
  'population': {'ages_0_25': 382933,
   'ages_25_50': 483923,
   'ages_over_50': 8898}},
 {'state': 'MN',
  'motto': 'Go pack go!',
  'num_of_counties': 87,
  'population': {'ages_0_25': 39323,
   'ages_25_50': 109282,
   'ages_over_50': 92837}},
 {'state': 'NV',
  'motto': 'all for our country',
  'num_of_counties': 16,
  'population': {'ages_0_25': 1923,
   'ages_25_50': 75832,
   'ages_over_50': 32743}}]

Question 4#

Using the list of values below create new lists made up of the following chunks:

  • The first 5 items in the list

  • The middle third of the list items

  • The first 3 items and the last 3 items together

# Creating my fake list -- this creates a list where each letter of the alphabet becomes its own item
alphabet = list('abcdefghijklmnopqrstuvwxyz')
  • The first 5 items in the list

alphabet[0:5]
# or
alphabet[:5]  # the 0 can optionally be dropped
['a', 'b', 'c', 'd', 'e']
  • The middle third of the list items

Method 1 - counting out the number of indexes and inputing them

alphabet
['a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'j',
 'k',
 'l',
 'm',
 'n',
 'o',
 'p',
 'q',
 'r',
 's',
 't',
 'u',
 'v',
 'w',
 'x',
 'y',
 'z']

Method 2 - Calculating the middle third based on the length of the list

# Calculating what each third's index should be, using floor division to ensure I get a whole integer as a result
thirds = len(alphabet) // 3
alphabet[thirds:thirds*2]
['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
  • The first 3 items and the last 3 items together

alphabet[:3] + alphabet[-3:]
['a', 'b', 'c', 'x', 'y', 'z']

Hint Googling suggestions: “python list indexing”, or “combining two python lists”. Article suggestions here or here.

Question 5#

Write some code that starts with an index and returns the value from the list below at that index. Print the value Include in the print statement if the value is even or odd.

starting_data = [4, 6, 4, 1, 3, 4, 6, 9, 8, 7, 6, 5, 5, 3, 2]
index = 3
value = starting_data[index]
if value % 2 == 0:
    print('value is ', value, 'which is even')
else:
    print('value is ', value, 'which is odd')
value is  1 which is odd