Lecture 3: Dictionaries and Program Control

In this lecture, you will learn:

A. Dictionaries in Python

Dictionaries are denoted by curly brackets { } (similar to sets). Dictionaries are somewhat like lists, but denoted by alphanumeric keys rather than integer indices. Here's what a dictionary data structure looks like:

In [1]:
solar_planets = {'Mercury': 2440.0, 'Venus': 6052.1, 'Earth': 6371.5, 'Mars': 3389.2, 'Jupiter': 69911.0, 'Saturn': 58232.2}
print(type(solar_planets), solar_planets)
<class 'dict'> {'Mercury': 2440.0, 'Venus': 6052.1, 'Earth': 6371.5, 'Mars': 3389.2, 'Jupiter': 69911.0, 'Saturn': 58232.2}

Each element in a dictionary has two aspects: key and value. To access a value, use the key with square brackets [ ]:

In [2]:
print(solar_planets['Venus'])
6052.1

Unlike standard dictionaries, you can change a key's value, add a new key, or remove keys using the del function:

In [5]:
solar_planets['Uranus'] = 25362.0  # add Uranus to the dict
del solar_planets['Earth']     # remove the key 'Earth'
print(solar_planets.keys())    # return the keys in a dictionary

B. Python Code Structures (Code Blocks)

Python uses INDENTATIONS to define the code blocks and make the code readable. This is one of the most distinctive features of Python.

In [10]:
food = input("What's your favorite food? ")

if food == 'garlic':
   print('I think', food, 'is super yucky')
else:
   print('I think', food, 'is super yummy')

Condition Statements

Common logic operators used for program control:

  • == : equals
  • != : does not equal
  • <, <=, >, >= : comparison
  • and / or : combine multiple tests

C. Program Control: If, While, and For Loops

C1. "if" and "if-elif-else"

The code-block is executed if the condition is true. elif (else if) and else handle additional conditions.

In [31]:
exam = 82.0
if exam >= 90.0:
    Grade = 'A'
elif exam >= 80.0:
    Grade = 'B'
else:
    Grade = 'Fail'
print('Your final grade is', Grade)

C2. "while" loops

A while loop executes a block as long as a condition is True.

In [35]:
N = 100
threshold = 90
while (N > threshold):
    print(N)
    N = N - 1
print('and the final value is: ', N)

C3. "for" loops

A for loop steps through a list and does something at each step.

In [37]:
mylist = ['jane', 'josh', 'sid', 'geoff']
for name in mylist:
    print(name)

D. Nested Loops - Put it all together

Below is an example of an if statement inside a for loop to identify habitable planets:

In [39]:
solar_planets = {'Mercury':440.0, 'Venus':737.1, 'Earth':288.5, 'Mars':210.2}

for key in solar_planets.keys():
    temperature = solar_planets[key] - 273.1 # Convert Kelvin to Celsius
 
    if (temperature <= 100) and (temperature >= -100):
        print('Planet', key, 'is habitable at', round(temperature, 1), '°C')
Planet Earth is habitable at 15.4 °C
Planet Mars is habitable at -62.9 °C