Lists and Dictionaries

Variables all have a type: String, Integer, Float, List and Dictionary are some key types. In Python, variables are given a type at assignment, Types are important to understand and will impact operations, as we saw when we were required to user str() function in concatenation.

#collapse-output
# Sample of Python Variables

# variable of type string
name = "Grace Wang"
print("name", name, type(name))

# variable of type integer
age = 16
print("age", age, type(age))

# variable of type float
score = 100
print("score", score, type(score))

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "R", "C", "html", "linux"]
print("langs", langs, type(langs))
print("- langs[0]", langs[0], type(langs[0]))

print()

# variable of type dictionary (a group of keys and values)
person = {
    "name": name,
    "age": age,
    "score": score,
    "langs": langs
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
name Grace Wang <class 'str'>
age 16 <class 'int'>
score 100 <class 'int'>
langs ['Python', 'JavaScript', 'Java', 'R', 'C', 'html', 'linux'] <class 'list'>
- langs[0] Python <class 'str'>

person {'name': 'Grace Wang', 'age': 16, 'score': 100, 'langs': ['Python', 'JavaScript', 'Java', 'R', 'C', 'html', 'linux']} <class 'dict'>
- person["name"] Grace Wang <class 'str'>

List and Dictionary purpose

List and Dictionaries are used to collect information. Mostly, when information is collected it is formed into patterns. As that pattern is established you will collect many instances of that pattern.

  • List is used to collect many
  • Dictionary is used to define data patterns.
  • Iteration is often used to process through lists.

#collapse-output
# Define an empty List called InfoDb
InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "FirstName": "John",
    "LastName": "Mortensen",
    "DOB": "October 21",
    "Residence": "San Diego",
    "Email": "jmortensen@powayusd.com",
    "Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Grace",
    "LastName": "Wang",
    "DOB": "September 2",
    "Residence": "San Diego",
    "Email": "gracewang187@gmail.com",
    "Owns_Cars": "None"
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'John', 'LastName': 'Mortensen', 'DOB': 'October 21', 'Residence': 'San Diego', 'Email': 'jmortensen@powayusd.com', 'Owns_Cars': ['2015-Fusion', '2011-Ranger', '2003-Excursion', '1997-F350', '1969-Cadillac']}, {'FirstName': 'Grace', 'LastName': 'Wang', 'DOB': 'September 2', 'Residence': 'San Diego', 'Email': 'gracewang187@gmail.com', 'Owns_Cars': 'None'}]

Formatted output of List/Dictionary - for loop

Managing data in Lists and Dictionaries is for the convenience of passing the data across the internet or preparing it to be stored into a database. Also, it is a great way to exchange data inside of our own programs.

Next, we will take the stored data and output it within our notebook. There are multiple steps to this process...

  • Preparing a function to format the data, the print_data() function receives a parameter called "d_rec" short for dictionary record. It then references different keys within [] square brackets.
  • Preparing a function to iterate through the list, the for_loop() function uses an enhanced for loop that pull record by record out of InfoDb until the list is empty. Each time through the loop it call print_data(record), which passes the dictionary record to that function.
  • Finally, you need to activate your function with the call to the defined function for_loop(). Functions are defined, not activated until they are called. By placing for_loop() at the left margin the function is activated.

#collapse-output
# given and index this will print InfoDb content
def print_data(d_rec):
    print(d_rec["FirstName"], d_rec["LastName"])  # using comma puts space between values
    print("\t", "Residence:", d_rec["Residence"]) # \t is a tab indent
    print("\t", "Birth Day:", d_rec["DOB"])
    print("\t", "Cars: ", end="")  # end="" make sure no return occurs
    print(", ".join(d_rec["Owns_Cars"]))  # join allows printing a string list with separator
    print()


# for loop iterates on length of InfoDb
def for_loop():
    print("For loop output\n")
    for record in InfoDb:
        print_data(record)

for_loop()
For loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Grace Wang
	 Residence: San Diego
	 Birth Day: September 2
	 Cars: N, o, n, e

Alternate methods for iteration - while loop

In coding, there are usually many ways to achieve the same result. Defined are functions illustrating using index to reference records in a list, these methods are called a "while" loop and "recursion".

  • The while_loop() function contains a while loop, "while i < len(InfoDb):". This counts through the elements in the list start at zero, and passes the record to print_data()

#collapse-output
# while loop contains an initial n and an index incrementing statement (n += 1)
def while_loop():
    print("While loop output\n")
    i = 0
    while i < len(InfoDb):
        record = InfoDb[i]
        print_data(record)
        i += 1
    return

while_loop()
While loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Grace Wang
	 Residence: San Diego
	 Birth Day: September 2
	 Cars: N, o, n, e

Calling a function repeatedly - recursion

This final technique achieves looping by calling itself repeatedly.

  • recursive_loop(i) function is primed with the value 0 on its activation with "recursive_loop(0)"
  • the last statement indented inside the if statement "recursive_loop(i + 1)" activates another call to the recursive_loop(i) function, each time i is increasing
  • ultimately the "if i < len(InfoDb):" will evaluate to false and the program ends

#collapse-output
# recursion simulates loop incrementing on each call (n + 1) until exit condition is met
def recursive_loop(i):
    if i < len(InfoDb):
        record = InfoDb[i]
        print_data(record)
        recursive_loop(i + 1)
    return
    
print("Recursive loop output\n")
recursive_loop(0)
Recursive loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Grace Wang
	 Residence: San Diego
	 Birth Day: September 2
	 Cars: N, o, n, e

My Own Dictionary

pip install pandas
Requirement already satisfied: pandas in /opt/homebrew/lib/python3.10/site-packages (1.4.4)
Requirement already satisfied: numpy>=1.21.0 in /opt/homebrew/lib/python3.10/site-packages (from pandas) (1.23.2)
Requirement already satisfied: pytz>=2020.1 in /opt/homebrew/lib/python3.10/site-packages (from pandas) (2022.2.1)
Requirement already satisfied: python-dateutil>=2.8.1 in /opt/homebrew/lib/python3.10/site-packages (from pandas) (2.8.2)
Requirement already satisfied: six>=1.5 in /opt/homebrew/lib/python3.10/site-packages (from python-dateutil>=2.8.1->pandas) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
import pandas as pd
data = {
    'Dates': ["8/17/22", "8/18/22", "8/19/22", "8/20/22", "8/21/22", "8/22/22", "8/23/22", "8/24/22", "8/25/22", "8/26/22", "8/27/22", "8/28/22", "8/29/22", "8/30/22", "8/31/22", "9/1/22", "9/2/22", "9/3/22", "9/4/22", "9/5/22"],
    'Hours': [8.5, 6.5, 7, 7, 9, 7, 12.5, 8, 8, 8, 8.5, 9, 8, 8, 7, 7, 6, 8, 9, 6.5]
}
def add_sleep_data():
    print("Add a day (Enter date in MM/DD/YY format): ")
    day = input()
    print("How many hours did you sleep? ")
    hours = input()
    # print(data["Dates"])
    data["Dates"].append(day)
    data["Hours"].append(hours)
    print("You added " + day + " : " + hours)
    print("Here is your updated sleep data")
    df_by_days = pd.DataFrame(data)
    print(df_by_days)

add_sleep_data()
Add a day (Enter date in MM/DD/YY format): 
How many hours did you sleep? 
You added 9/6/22 : 9
Here is your updated sleep data
      Dates Hours
0   8/17/22   8.5
1   8/18/22   6.5
2   8/19/22     7
3   8/20/22     7
4   8/21/22     9
5   8/22/22     7
6   8/23/22  12.5
7   8/24/22     8
8   8/25/22     8
9   8/26/22     8
10  8/27/22   8.5
11  8/28/22     9
12  8/29/22     8
13  8/30/22     8
14  8/31/22     7
15   9/1/22     7
16   9/2/22     6
17   9/3/22     8
18   9/4/22     9
19   9/5/22   6.5
20   9/6/22     9
data2 = {}
for hours in data["Hours"]:
    data2[hours] = 0

def print_hour_freq(data, freq_dict):
    i = 0
    while i < len(data):
        for key in freq_dict.keys():
            if data[i] == key:
                freq_dict[key] += 1
        i += 1
    print(freq_dict)

print_hour_freq(data["Hours"], data2)
{8.5: 2, 6.5: 2, 7: 5, 9: 3, 12.5: 1, 8: 6, 6: 1, '9': 1}
df_by_days = pd.DataFrame(data)
print(df_by_days)
      Dates Hours
0   8/17/22   8.5
1   8/18/22   6.5
2   8/19/22     7
3   8/20/22     7
4   8/21/22     9
5   8/22/22     7
6   8/23/22  12.5
7   8/24/22     8
8   8/25/22     8
9   8/26/22     8
10  8/27/22   8.5
11  8/28/22     9
12  8/29/22     8
13  8/30/22     8
14  8/31/22     7
15   9/1/22     7
16   9/2/22     6
17   9/3/22     8
18   9/4/22     9
19   9/5/22   6.5
20   9/6/22     9
df_by_days['Hours'] = df_by_days['Hours'].astype(float)
df_by_days.dtypes
Dates     object
Hours    float64
dtype: object
df_by_days.plot(x = "Dates", y = "Hours", kind = "line", color = "pink")
<AxesSubplot:xlabel='Dates'>

Python Quiz with Dictionaries

score = 0

question_answer = {
    "What command defines a function or method?": "def",
    "What conditionally executes a block of code, along with else and elif?": "if statement",
    "What does a jupyter notebook end in?": "ipynb",
    "What is style of programming characterized by the identification of classes of objects closely linked with the methods?": "object oriented programming",
    "What is the text at the front of a markdown post called?": "front matter" 
    }

def ask_question(question, answer):
    """Asks question and determines if """
    print(question)
    user_answer = ask_for_answer()
    is_answer_right(user_answer, answer)

def ask_for_answer():
    """Asks for an input from the user and returns user answer"""
    answer = input().lower()
    print(answer)
    return answer

def is_answer_right(user_answer, answer):
    """Inputs user answer and actual answer and adds to score if answer is right"""
    global score
    if user_answer == answer:
        score += 1
        print(f"Good job! The answer is {answer}!")
    else:
        print(f"Sorry, incorrect 😒. The right answer was {answer}.")
    print(f"Your score is {score}.")
print("Welcome to Grace's Quiz!")

start = input("Do you want to take Grace's Quiz?")

#Start game dialogue
if start.lower() == "yes" or start.lower() == "y":
    print("Great! Good luck 😊")
else:
    print("Take a mindful minute. You got this :)")
    print("This game will have 5 questions!")

i = 0
#Loop to ask questions
while i < len(question_answer):
    answer = list(question_answer.values())[i]
    question = list(question_answer.keys())[i]
    ask_question(question, answer)
    i += 1

#Prints a message depending on what score user got
if score == 5:
    print("Wow! You know your stuff! Keep up the good work! πŸ€—")
if score == 4:
    print("Almost! Try again.")
if score <= 3:
    print("You're average 😐 ")
Welcome to Grace's Quiz!
Great! Good luck 😊
What command defines a function or method?
def
Good job! The answer is def!
Your score is 1.
What conditionally executes a block of code, along with else and elif?
if statement
Good job! The answer is if statement!
Your score is 2.
What does a jupyter notebook end in?
ipynb
Good job! The answer is ipynb!
Your score is 3.
What is style of programming characterized by the identification of classes of objects closely linked with the methods?
object oriented programming
Good job! The answer is object oriented programming!
Your score is 4.
What is the text at the front of a markdown post called?
object oriented programming
Sorry, incorrect 😒. The right answer was front matter.
Your score is 4.
Almost! Try again.