Lists, Dictionaries, and Iterations (and Quiz That Stores Dictionaries)
Here you will find code that involves the use of for, while, and recursive loops in order to print out specific data. Additonally, there is a quiz that incorporates dictionaries in order to collect information.
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.
Developers often think of variables as primitives or collections. Look at this example and see if you can see hypothesize the difference between a primitive and a collection. Take a minute and see if you can reference other elements in the list or other keys in the dictionary. Show output.
import random
# variable of type string
name = "Emaad Mir"
print("Name:", name, type(name))
# variable of type integer
age = 15
print("Age:", age, type(age))
# variable of type float
grade = 105.9
print("Grade:", grade, type(grade))
# another variable of type string
fav_song = "Running Up That Hill"
print("Favorite Song:", fav_song, type(fav_song))
print()
# variable of type list (many values in one variable)
langs = ["Python", "Html", "CSS", "C", "Java", "JavaScript", "C", "R"]
random_lang = random.choice(langs)
print("Random Language:", random_lang)
games = ["Super Mario", "Kirby", "Wii Sports Resort", "Subway Surfer"]
random_game = random.choice(games)
print("Random Game:", random_game)
print()
# variable of type dictionary (a group of keys and values)
person = {
"Name": name,
"Age": age,
"Grade": grade,
"Languages": langs,
"Favorite Song": fav_song
}
# prints what is in the person dictionary without brackets
print(*[str(k) + ':' + str(v) for k,v in person.items()])
# LISTS THE FOOD IN REVERSE ORDER
foods = ["Bread", "Pizza", "Burgers", "Chocolate Cake", "Salad", "Fried Rice", "Noodles"]
foods.reverse()
print('\nReversed List:'),
print(', '.join(foods))
# LISTS THE FOOD IN A RANDOM ORDER
random.shuffle(foods)
print('\nRandom Order:'),
print(', '.join(foods))
List and Dictionary Purpose
Lists and Dictionaries are used to collect information. Mostly, when information is collected, it is formed into patterns. As that pattern is established you will be able collect many instances of that pattern.
List is used to collect many instances of a pattern
Dictionary is used to define data patterns.
Iteration is often used to process through lists.
To start exploring more deeply into List, Dictionary and Iteration this example will explore constructing a List of people and hobbies.
As we learned above, a List is a data type: class 'list' A 'list' data type has the method '.append(expression)' that allows you to add to the list. A class usually has extra method to support working with its objects/instances. In the example below, the expression is appended to the 'list' is the data type: class 'dict' At the end, you see a fairly complicated data structure. This is a list of dictionaries, or a collection of many similar data patterns. The output looks similar to JavaScript Object Notation (JSON), Jekyll/GitHub pages yml files, FastPages Front Matter. As discussed we will see this key/value patter often, you will be required to understand this data structure and understand the parts. Just believe it is peasy ;) and it will become so.
InfoDb = []
# InfoDB is a data structure with expected Keys and Values
# Append to List a Dictionary of key/values related to a person and hobbies
InfoDb.append({
"FirstName": "Emaad",
"LastName": "Mir",
"DOB": "January 12",
"Email": "emaadidrismir@gmail.com",
"FavoriteFoods": ["French Fries, Ice Cream, Bananas, Pizza"],
"Hobbies": ["Playing Squash", "Sleeping", "Hiking", "Cooking", "Playing Basketball"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Edwin",
"LastName": "Abraham",
"DOB": "August 7",
"Email": "edwinab0007@gmail.com",
"FavoriteFoods": ["Burgers, Pizza, Brownies, Watermelon"],
"Hobbies": ["Biking","Hiking", "Playing Video Games"]
})
# 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, to applications, or preparing it to be stored into a database. It is a great way to exchange data between programs and programmers. Exchange of data between programs includes the data type the method/function and the format of the data type. These concepts are key to learning how to write functions, receive, and return data. This process is often referred to as an Application Programming Interface (API).
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.
def print_data(person): # defines the data being printed
print("Name:", person["FirstName"], person["LastName"]) # Tells the computer to print certain things from the dictionary
print("Birthday:", person["DOB"])
print("Email:", person["Email"])
print("FavoriteFoods:", ", ".join(person["FavoriteFoods"]))
print("Hobbies:", ", ".join(person["Hobbies"]))
print()
print_data(InfoDb[0]) # Prints the data of the first person (Emaad Mir)
def for_loop(): # for every person in the InfoDB, print their data until there is nothing else to print
for person in InfoDb:
print_data(person)
def for_loop_with_index(): # prints out data depending on the length of the dictionary it comes from
for i in range(len(InfoDb)):
print_data(InfoDb[i])
print("REGULAR FOR LOOP OUTPUT\n")
for_loop()
print("FOR LOOP WITH INDEX OUTPUT\n")
for_loop_with_index()
While Loops
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()
def while_loop(): # i starts at 0
i = 0
while i < len(InfoDb): # while i is less than the length of the dictionary (2), keep printing the people's data
print_data(InfoDb[i])
i = i + 1
def while_loop_reverse(): # this does the same thing as described above, except it prints in reverse order
i = len(InfoDb) - 1
while i >= 0:
print_data(InfoDb[i])
i = i -1
print("REGULAR WHILE LOOP\n") # labels the regular and reversed version of the list of people and their info
while_loop()
print("REVERSED WHILE LOOP\n")
while_loop_reverse()
Recursive Loops
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
def recursive(index): # the recursive loop will keep calling itself until it is greater than or equal to the length of the dictionary
if index >= len(InfoDb):
return # this is where the code will end
print_data(InfoDb[index]) # prints the data and keeps printing until it has reached the length of the dictionary
return recursive(index + 1)
print("RECURSIVE INDEX OUTPUT\n")
recursive(0) # the computer will begin printing person 0's data and keep calling itself until there are no more people left
grade_level = {}
for i in range(1):
student_name = input("Enter the student's full name ")
student_grade = input("Enter the student's grade level")
grade_level[student_name] = student_grade
print(grade_level)
import getpass, sys
def question_and_answer(prompt):
print("Question:" +prompt)
msg = input("Question:" +prompt)
print("Answer:" +msg)
## defines the format of how the question will be asked
def question_with_response(prompt):
print("Question: " + prompt)
msg = input("Question: " + prompt)
return msg
qa_list = [] # Shows the list of questions and answers
qa_list.append({
"Question": "What syntax allows you to format and pass variables in html?",
"Answer": "liquid",
})
qa_list.append({
"Question": "What is the instructions for what you want a computer to do called?",
"Answer": "input",
})
qa_list.append({
"Question": "What is the name of the theme that your webpage has by default?",
"Answer": "minima",
})
qa_list.append({
"Question": "_______ involves calling itself repeatedly in order to achieve looping",
"Answer": "recursion",
})
qa_list.append({
"Question": "Lists and ________ are used to collect information",
"Answer": "dictionaries",
})
qa_list.append({
"Question": "What is the name of the file that the style directory is stored in (just the name, don't need the type of file)?",
"Answer": "sass"
})
questions = len(qa_list) # number of questions equals the length of the list of questions and answers
score = 0 # this is the score the user will begin with
print('Hello, ' + getpass.getuser() + " running " + sys.executable) # user will be prompted with this message before taking the quiz
print("You will be asked " + str(questions) + " questions.")
response = question_with_response("Are you ready to take a test?")
if response == "yes": # if user types in yes, the quiz will commence
print("You said yes, so let's get started!")
for q in qa_list:
print(q["Question"])
response = input(q["Question"])
if response == q["Answer"]:
print(response + " is correct! Great job!") # if the answer the user types in matches what is on the list, the user will get a point added to score
score = score + 1
else: # if the user types something that doesn't match what's on the list, the user won't get a point
print(response + " is incorrect! Sorry!")
print(getpass.getuser() + ", you scored " + str(score) +"/" + str(questions) + ", which is " + str((score / questions) * 100) + "%")
else:
print("Maybe another time!") # if the user responds with no to the first prompt, the user will have this message and the code will end