Lists, Dictionaries, Iteration
An introduction to Data Abstraction using Python Lists [] and Python Dictionaries {}.
- Lists and Dictionaries
- List and Dictionary purpose
- Formatted output of List/Dictionary - for loop
- Alternate methods for iteration - while loop
- Calling a function repeatedly - recursion
- My Own Dictionary
- Python Quiz with Dictionaries
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"]))
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)
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()
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()
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)
pip install pandas
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()
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)
df_by_days = pd.DataFrame(data)
print(df_by_days)
df_by_days['Hours'] = df_by_days['Hours'].astype(float)
df_by_days.dtypes
df_by_days.plot(x = "Dates", y = "Hours", kind = "line", color = "pink")
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 π ")