Lists, Dictioinaries, Iteration
An introduction to python lists and dictionaries!
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.
A 'list' data type has the method '.append(expression)' that allows you to add to the list. At the end, you see a fairly complicated data structure. This is a list of dictionaries, or a collection of many similar data patterns.
In the code below, information about two different pets are being added into the dictionary using the append method.
InfoDb = []
# InfoDB is a data structure with expected Keys and Values, in this case
# Append to List a Dictionary of key/values related to pets
InfoDb.append({
"Species": "Cat",
"Name": "Apollo",
"Nickname": "Bingus",
"Age": "2 years",
"Owner": "Aliya",
"Fur_Color": ["Orange"],
"Eye_Color": "Green",
"Fav_Toy": ["Shoe", "Laser Pointer", "Plastic Wrap","Box"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"Species": "Cat",
"Name": "Luca",
"Nickname": "Mart",
"Age": "2 years",
"Owner": "Alice",
"Fur_Color": ["Orange","White"],
"Eye_Color": "Yellow",
"Fav_Toy": ["Mouse Plush","Box","String"]
})
# Print the data structure
print(InfoDb)
def print_data(d_rec):
print(d_rec["Name"], "the", d_rec["Species"]) # using comma puts space between values
print("\t", "Owner:", d_rec["Owner"]) #\t is tab
print("\t", "Nickname:", d_rec["Nickname"])
print("\t", "Age:", d_rec["Age"])
print("\t","Traits: ", end="")
print(" + ".join(d_rec["Fur_Color"]), "fur with", d_rec["Eye_Color"], "eyes") #putting multiple values in one section (traits)
print("\t", "Favorite Toy(s): ", end="") #the end makes sure it doesn't enter to a new line
print(", ".join(d_rec["Fav_Toy"]))
print()
# for loop algorithm iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
While Loop
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()
In the code below, the while loop outputs the information about the pets. The program doesn't end as long as the variable number (i) is less than the length of the InfoDb list.
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()
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)
QuizDb = {"China":"beijing",
"United States":"washington dc",
"Canada":"ottowa",
"Russia":"moscow",
"Japan":"tokyo"}
correct = 0
def q_and_a(q):
print("What is the capital of " + q + "?:", flush=True)
user_input = input().strip()
if QuizDb[q] == user_input.lower(): #converts what user typed into lowercase to prevent mistakes
print(user_input + " is correct! Nice job.", flush=True)
return 1
else:
print(user_input + " is incorrect. Oops!", flush=True)
return 0
correct += q_and_a("China")
correct += q_and_a("United States")
correct += q_and_a("Canada")
correct += q_and_a("Russia")
correct += q_and_a("Japan")
print("Nice try, you got " + str(correct) + "/5 correct.")