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)
[{'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']}, {'Species': 'Cat', 'Name': 'Luca', 'Nickname': 'Mart', 'Age': '2 years', 'Owner': 'Alice', 'Fur_Color': ['Orange', 'White'], 'Eye_Color': 'Yellow', 'Fav_Toy': ['Mouse Plush', 'Box', 'String']}]

For Loop

In the code below, we take the stored data about the pets and output/print it in the notebook. First we prepare a function to format the data, then a function to iterate through the InfoDb list, and lastly activate the function with the call to the defined function.

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()
For loop output

Apollo the Cat
	 Owner: Aliya
	 Nickname: Bingus
	 Age: 2 years
	 Traits: Orange fur with Green eyes
	 Favorite Toy(s): Shoe, Laser Pointer, Plastic Wrap, Box

Luca the Cat
	 Owner: Alice
	 Nickname: Mart
	 Age: 2 years
	 Traits: Orange + White fur with Yellow eyes
	 Favorite Toy(s): Mouse Plush, Box, String

Alternate methods for iteration

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

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()
While loop output

Apollo the Cat
	 Owner: Aliya
	 Nickname: Bingus
	 Age: 2 years
	 Traits: Orange fur with Green eyes
	 Favorite Toy(s): Shoe, Laser Pointer, Plastic Wrap, Box

Luca the Cat
	 Owner: Alice
	 Nickname: Mart
	 Age: 2 years
	 Traits: Orange + White fur with Yellow eyes
	 Favorite Toy(s): Mouse Plush, Box, String

Recursion

The code below prints information about the pets with recursion by calling itself repeatedly. The progam ends once the i value exceeds the length of the InfoDb length, just like the 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)
Recursive loop output

Apollo the Cat
	 Owner: Aliya
	 Nickname: Bingus
	 Age: 2 years
	 Traits: Orange fur with Green eyes
	 Favorite Toy(s): Shoe, Laser Pointer, Plastic Wrap, Box

Luca the Cat
	 Owner: Alice
	 Nickname: Mart
	 Age: 2 years
	 Traits: Orange + White fur with Yellow eyes
	 Favorite Toy(s): Mouse Plush, Box, String

Quiz

This is a quiz about the capitals of different countries that stores information in a list of dictionaries.

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.")
What is the capital of China?:
beijing is correct! Nice job.
What is the capital of United States?:
washington dc is correct! Nice job.
What is the capital of Canada?:
Ottowa is correct! Nice job.
What is the capital of Russia?:
Moscow is correct! Nice job.
What is the capital of Japan?:
hi is incorrect. Oops!
Nice try, you got 4/5 correct.