1.4. Python Basics III: Lists, Dictionaries, and Enumeration#

Reference: Chapters 2 and 5 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)

1.4.1. Learning Objectives#

After studying this notebook, completing the activities, and asking questions in class, you should be able to:

  • Create lists with numeric and non-numeric items and add to a previously created list.

  • Enumerate a list using various syntax.

  • Create dictionaries with numeric and non-numeric key-value pairs and add to a previously created dictionary.

  • Enumerate a dictionary using various syntax.

1.4.2. Lists#

You can also do other fun stuff with for loops. For instance, you can have the control variable take on non-numeric things:

#silly hat code
hats = ["fedora","trilby","porkpie","tam o'shanter",
        "Phrygian cap","Beefeaters' hat","sombrero"]
days = ["Monday","Tuesday","Wednesday","Thursday",
        "Friday","Saturday","Sunday"]
count = 0
for today in hats:
    print("It is",days[count],"and I will wear a",today)
    count += 1
It is Monday and I will wear a fedora
It is Tuesday and I will wear a trilby
It is Wednesday and I will wear a porkpie
It is Thursday and I will wear a tam o'shanter
It is Friday and I will wear a Phrygian cap
It is Saturday and I will wear a Beefeaters' hat
It is Sunday and I will wear a sombrero

Notice what else we did here: we defined a list called days that contained strings for the names of the days of the week. Inside our for loop we had a numeric variable that kept track of what number the day of the week was (0 for Monday in this case). Then when we access days[count] it returns the string in position count.

We can go one step beyond and plan our wardrobe a month in advance using random numbers. The code below generates a random integer between 0 and 6:

import random
my_random_number = round(random.uniform(0,6))
print(my_random_number)
1

Home Activity

Modify the code below to loop over 30 days. For each day, randomly select which hat to wear.

#silly hat code
import random
hats = ["fedora","trilby","porkpie","tam o'shanter",
        "Phrygian cap","Beefeaters' hat","sombrero"]
days = ["Monday","Tuesday","Wednesday","Thursday",
        "Friday","Saturday","Sunday"]

# loop over 30 days
# Add your solution here

    # randomly select a hat to wear
    # Add your solution here
    
    # print which day of the week it is and the hat choice
    # Add your solution here

Lists are like vectors in MATLAB, except, as you can see above, we can store more than just numbers in them. We will talk about using a package numpy to represent vectors and matrices in the NumPy notebook.

Home Activity

Fix the three examples below to count from 1 to 10.

## Attempt 1
N = [1, 2, 3, 4, 5, 6, 7, 11]
for i in range(len(N)):
    print(i+1)
1
2
3
4
5
6
7
8
# Add your solution here
## Attempt 2
N = [1, 2, 3, 4, 5, 6, 7, 11]
for i in range(len(N)):
    print(N[i])
1
2
3
4
5
6
7
11
# Add your solution here
## Attempt 3
for i in range(0,10):
    print(i)
0
1
2
3
4
5
6
7
8
9
# Add your solution here

1.4.3. Dictionaries#

So far, we have used lists to store a sequence of numbers or more generally Python objects. Lists (and NumPy arrays - stay tuned) access elements by position and have an inherent ordering.

A dictionary is a set of key : value pairs. You can think of a dictionary as a fancy list that instead of accessing via the position, you access using a key.

#simple dictionary
days_of_week = {"M":"Monday", "T":"Tuesday",
                "W":"Wednesday", "R":"Thursday",
                "F":"Friday", "S":"Saturday",
                "U":"Sunday"}

print("Key M gives", days_of_week["M"])
print("Key R gives", days_of_week["R"])
Key M gives Monday
Key R gives Thursday

Home Activity

Store the value for key F in the variable answer.

# Add your solution here
# Removed autograder test. You may delete this cell.

Calling days_of_week.keys() returns a special list of the keys of the dictionary.

print(days_of_week.keys())
dict_keys(['M', 'T', 'W', 'R', 'F', 'S', 'U'])

We can also check if G is a valid key for the dictionary.

print("G" in days_of_week.keys()) #is G a key in days_of_week?
False

Main idea: With dictionaries, we access elements using the key. In contrast, we access elements of strings, lists, and Numpy arrays using the position.

1.4.4. Example: Shopping List#

Home Activity

Create a dictionary to store the following shopping list. The keys should be the item names and the elements should be the quantity of the items.

  • 1.5 bananas (pounds)

  • 3 cans of soup

  • 6 apples

  • 2.3 pork tenderloin (pounds)

# Add your solution here
# Removed autograder test. You may delete this cell.

1.4.5. Another Example: Chemical Symbols and Element Names#

Below is code that parses ChemicalSymbols.csv and stores the data in dictionary.

import csv
element_dict = {} #create a blank dictionary

# this block will only execute if the file opens
with open('https://raw.githubusercontent.com/ndcbe/data-and-computing/main/notebooks/data/ChemicalSymbols.csv') as csvfile: 
    chemreader = csv.reader(csvfile)
    for row in chemreader: # have for loop that loops over each line
        element_dict[row[0]] = row[1] # add a key:value pair

# Ask user to enter a chemical symbol        
key = input("Enter a valid chemical symbol: ")
if key in element_dict:
    print(key,"is",element_dict[key])
else:
    print("Not a valid element")
K is Potassium

Home Activity

Run the code above twice. Try first with a valid chemical symbol. Then try with a chemical symbol not on the periodic table of elements.

We can also print out the dictionary.

print(element_dict)
{'Ac': 'Actinium', 'Ag': 'Silver', 'Al': 'Aluminium (Aluminum)', 'Am': 'Americium', 'Ar': 'Argon', 'As': 'Arsenic', 'At': 'Astatine', 'Au': 'Gold', 'B': 'Boron', 'Ba': 'Barium', 'Be': 'Beryllium', 'Bh': 'Bohrium', 'Bi': 'Bismuth', 'Bk': 'Berkelium', 'Br': 'Bromine', 'C': 'Carbon', 'Ca': 'Calcium', 'Cd': 'Cadmium', 'Ce': 'Cerium', 'Cf': 'Californium', 'Cl': 'Chlorine', 'Cm': 'Curium', 'Cn': 'Copernicium', 'Co': 'Cobalt', 'Cr': 'Chromium', 'Cs': 'Caesium (Cesium)', 'Cu': 'Copper', 'Db': 'Dubnium', 'Ds': 'Darmstadtium', 'Dy': 'Dysprosium', 'Er': 'Erbium', 'Es': 'Einsteinium', 'Eu': 'Europium', 'F': 'Fluorine', 'Fe': 'Iron', 'Fl': 'Flerovium', 'Fm': 'Fermium', 'Fr': 'Francium', 'Ga': 'Gallium', 'Gd': 'Gadolinium', 'Ge': 'Germanium', 'H': 'Hydrogen', 'He': 'Helium', 'Hf': 'Hafnium', 'Hg': 'Mercury', 'Ho': 'Holmium', 'Hs': 'Hassium', 'I': 'Iodine', 'In': 'Indium', 'Ir': 'Iridium', 'K': 'Potassium', 'Kr': 'Krypton', 'La': 'Lanthanum', 'Li': 'Lithium', 'Lr': 'Lawrencium', 'Lu': 'Lutetium', 'Lv': 'Livermorium', 'Md': 'Mendelevium', 'Mg': 'Magnesium', 'Mn': 'Manganese', 'Mo': 'Molybdenum', 'Mt': 'Meitnerium', 'N': 'Nitrogen', 'Na': 'Sodium', 'Nb': 'Niobium', 'Nd': 'Neodymium', 'Ne': 'Neon', 'Ni': 'Nickel', 'No': 'Nobelium', 'Np': 'Neptunium', 'O': 'Oxygen', 'Os': 'Osmium', 'P': 'Phosphorus', 'Pa': 'Protactinium', 'Pb': 'Lead', 'Pd': 'Palladium', 'Pm': 'Promethium', 'Po': 'Polonium', 'Pr': 'Praseodymium', 'Pt': 'Platinum', 'Pu': 'Plutonium', 'Ra': 'Radium', 'Rb': 'Rubidium', 'Re': 'Rhenium', 'Rf': 'Rutherfordium', 'Rg': 'Roentgenium', 'Rh': 'Rhodium', 'Rn': 'Radon', 'Ru': 'Ruthenium', 'S': 'Sulfur (Sulphur)', 'Sb': 'Antimony', 'Sc': 'Scandium', 'Se': 'Selenium', 'Sg': 'Seaborgium', 'Si': 'Silicon', 'Sm': 'Samarium', 'Sn': 'Tin', 'Sr': 'Strontium', 'Ta': 'Tantalum', 'Tb': 'Terbium', 'Tc': 'Technetium', 'Te': 'Tellurium', 'Th': 'Thorium', 'Ti': 'Titanium', 'Tl': 'Thallium', 'Tm': 'Thulium', 'U': 'Uranium', 'Uuo': 'Ununoctium', 'Uup': 'Ununpentium', 'Uus': 'Ununseptium', 'Uut': 'Ununtrium', 'V': 'Vanadium', 'W': 'Tungsten', 'Xe': 'Xenon', 'Y': 'Yttrium', 'Yb': 'Ytterbium', 'Zn': 'Zinc', 'Zr': 'Zirconium'}
element_dict
Hide code cell output
{'Ac': 'Actinium',
 'Ag': 'Silver',
 'Al': 'Aluminium (Aluminum)',
 'Am': 'Americium',
 'Ar': 'Argon',
 'As': 'Arsenic',
 'At': 'Astatine',
 'Au': 'Gold',
 'B': 'Boron',
 'Ba': 'Barium',
 'Be': 'Beryllium',
 'Bh': 'Bohrium',
 'Bi': 'Bismuth',
 'Bk': 'Berkelium',
 'Br': 'Bromine',
 'C': 'Carbon',
 'Ca': 'Calcium',
 'Cd': 'Cadmium',
 'Ce': 'Cerium',
 'Cf': 'Californium',
 'Cl': 'Chlorine',
 'Cm': 'Curium',
 'Cn': 'Copernicium',
 'Co': 'Cobalt',
 'Cr': 'Chromium',
 'Cs': 'Caesium (Cesium)',
 'Cu': 'Copper',
 'Db': 'Dubnium',
 'Ds': 'Darmstadtium',
 'Dy': 'Dysprosium',
 'Er': 'Erbium',
 'Es': 'Einsteinium',
 'Eu': 'Europium',
 'F': 'Fluorine',
 'Fe': 'Iron',
 'Fl': 'Flerovium',
 'Fm': 'Fermium',
 'Fr': 'Francium',
 'Ga': 'Gallium',
 'Gd': 'Gadolinium',
 'Ge': 'Germanium',
 'H': 'Hydrogen',
 'He': 'Helium',
 'Hf': 'Hafnium',
 'Hg': 'Mercury',
 'Ho': 'Holmium',
 'Hs': 'Hassium',
 'I': 'Iodine',
 'In': 'Indium',
 'Ir': 'Iridium',
 'K': 'Potassium',
 'Kr': 'Krypton',
 'La': 'Lanthanum',
 'Li': 'Lithium',
 'Lr': 'Lawrencium',
 'Lu': 'Lutetium',
 'Lv': 'Livermorium',
 'Md': 'Mendelevium',
 'Mg': 'Magnesium',
 'Mn': 'Manganese',
 'Mo': 'Molybdenum',
 'Mt': 'Meitnerium',
 'N': 'Nitrogen',
 'Na': 'Sodium',
 'Nb': 'Niobium',
 'Nd': 'Neodymium',
 'Ne': 'Neon',
 'Ni': 'Nickel',
 'No': 'Nobelium',
 'Np': 'Neptunium',
 'O': 'Oxygen',
 'Os': 'Osmium',
 'P': 'Phosphorus',
 'Pa': 'Protactinium',
 'Pb': 'Lead',
 'Pd': 'Palladium',
 'Pm': 'Promethium',
 'Po': 'Polonium',
 'Pr': 'Praseodymium',
 'Pt': 'Platinum',
 'Pu': 'Plutonium',
 'Ra': 'Radium',
 'Rb': 'Rubidium',
 'Re': 'Rhenium',
 'Rf': 'Rutherfordium',
 'Rg': 'Roentgenium',
 'Rh': 'Rhodium',
 'Rn': 'Radon',
 'Ru': 'Ruthenium',
 'S': 'Sulfur (Sulphur)',
 'Sb': 'Antimony',
 'Sc': 'Scandium',
 'Se': 'Selenium',
 'Sg': 'Seaborgium',
 'Si': 'Silicon',
 'Sm': 'Samarium',
 'Sn': 'Tin',
 'Sr': 'Strontium',
 'Ta': 'Tantalum',
 'Tb': 'Terbium',
 'Tc': 'Technetium',
 'Te': 'Tellurium',
 'Th': 'Thorium',
 'Ti': 'Titanium',
 'Tl': 'Thallium',
 'Tm': 'Thulium',
 'U': 'Uranium',
 'Uuo': 'Ununoctium',
 'Uup': 'Ununpentium',
 'Uus': 'Ununseptium',
 'Uut': 'Ununtrium',
 'V': 'Vanadium',
 'W': 'Tungsten',
 'Xe': 'Xenon',
 'Y': 'Yttrium',
 'Yb': 'Ytterbium',
 'Zn': 'Zinc',
 'Zr': 'Zirconium'}

1.4.6. Dictionary of Dictionaries#

We can make dictionaries even more powerful if we make a dictionary of dictionaries.

Top Level. Day of the week.

  • Key: symbol “M”, “T”, etc.

  • Value: Another dictionary!

Second Level. Data for each day.

  • Keys: “name”, “weekday”, “weekend”

  • Values: string, boolean (True or False), boolean

#simple dictionary of dictionaries
days_of_week = {"M":{"name":"Monday","weekday":True,"weekend":False},
                "T":{"name":"Tuesday","weekday":True,"weekend":False},
                "W":{"name":"Wednesday","weekday":True,"weekend":False},
                "R":{"name":"Thursday","weekday":True,"weekend":False},
                "F":{"name":"Friday","weekday":True,"weekend":False},
                "S":{"name":"Saturday","weekday":False,"weekend":True},
                "U":{"name":"Sunday","weekday":False,"weekend":True}}

print("The days that are weekdays are")
for day in days_of_week: #for loop over dictionary, loops over keys
    if days_of_week[day]["weekday"] == True:
        print(days_of_week[day]["name"],"is a weekday.")

print("The days that are weekend days are")        
for day in days_of_week: #for loop over dictionary, loops over keys
    if days_of_week[day]["weekend"] == True:
        print(days_of_week[day]["name"],"is a weekend, whoop.")
The days that are weekdays are
Monday is a weekday.
Tuesday is a weekday.
Wednesday is a weekday.
Thursday is a weekday.
Friday is a weekday.
The days that are weekend days are
Saturday is a weekend, whoop.
Sunday is a weekend, whoop.

Notice that when you loop over a dictionary in a for loop, the loop variable will get each of the keys of the dictionary.

The dictionary has been modified to include the day name in Spanish.

#more complicated dictionary of dictionaries
days_of_week2 = {"M":{"name":"Monday","weekday":True,"Spanish":"Lunes"},
                "T":{"name":"Tuesday","weekday":True,"Spanish":"Martes"},
                "W":{"name":"Wednesday","weekday":True,"Spanish":"Miércoles"},
                "R":{"name":"Thursday","weekday":True,"Spanish":"Jueves"},
                "F":{"name":"Friday","weekday":True,"Spanish":"Viernes"},
                "S":{"name":"Saturday","weekday":False,"Spanish":"Sábado"},
                "U":{"name":"Sunday","weekday":False,"Spanish":"Domingo"}}

Class Activity

With a partner, write pseudocode to loop over the days of the week. Print off the day name in Spanish and whether it is a weekend or weekday.

Class Activity

Implement your pseudocode in Python.

# Add your solution here

1.4.7. Enumerate#

1.4.8. Lists#

Let’s see some syntax for growing lists.

# create a list with nothing

students = []

# add a student
students.append("Joe Smith")

# add another student
students.append("Jane Doe")
print(students)
['Joe Smith', 'Jane Doe']

How to loop over the list? Let’s review.

# Approach 1
for s in students:
    print(s)
Joe Smith
Jane Doe
# Approach 2
for i in range(len(students)):
    print(i,": ",students[i])
0 :  Joe Smith
1 :  Jane Doe

Can we simply the syntax? It is really convienent to access the index with i and the student with s.

for i, s in enumerate(students):
    print(i,": ",s)
0 :  Joe Smith
1 :  Jane Doe

1.4.9. Dictionaries#

How about adding key-value pairs to a dictionary? Let’s take a look.

# create a dictionary with nothing

pantry = {}

# add a pantry item and quantity
pantry["pasta"] = 3

# add another pantry item and quantity
pantry["green beans"] = 4
print(pantry)
{'pasta': 3, 'green beans': 4}

If the key already exists in the dictionary, it will update with the newly assigned value rather than add another pair.

pantry["pasta"] = 2
print(pantry)
{'pasta': 2, 'green beans': 4}

How do we loop over the dictionary? Here it is again.

# to print out just the keys
for k in pantry.keys():
    print(k)
pasta
green beans
# to print out just the values
for v in pantry.values():
    print(v)
2
4
# to print out the key-value pairs together
for food in pantry:
    print(food, ":", pantry[food])
pasta : 2
green beans : 4