Lists and Dictionaries

As a quick review we used variables in the introduction last week.

These examples can show the difference between a primitive and a collection

name = "Edwin A"
print("What is the variable value,", name)
What is the variable value, Edwin A
import random

# variable of type string
name = "Edwin Abraham"
print("Name:", name, type(name))

age = 16 # Integer Type of Variable
print("age", age, type(age))

score = 104.1 # Float Type of Variable
print("score", score, type(score))

grade = 11 # Integer Type
print ("Grade Level:", grade, type(grade))

email = "edwinab0007@gmail.com"
print ("Email:", email, type(email))

print()

# Multiple variables in a single list and printing the whole list
langs = ["Python", "HTML", "CSS", "C", "R", "Lua", "Java"]
random_lang = random.choice(langs)
print("langs", langs, type(langs))
print("- langs[0]", langs[1], type(langs[1]))
print ("One Language:", random_lang)

foods = ["Burger", "Pizza", "Ice Cream", "Brownie,", "Paratha"]
random_car = random.choice(foods)
print("Food:", foods, type(foods) )
print("Random Food:", random_car)

print()

# variable of type dictionary (a group of keys and values)
person = { # Variable used later and helps store the data
    "name": name,
    "age": age,
    "grade": grade,
    "Language": langs,
    "Email": email
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
Name: Edwin Abraham <class 'str'>
age 16 <class 'int'>
score 104.1 <class 'float'>
Grade Level: 11 <class 'int'>
Email: edwinab0007@gmail.com <class 'str'>

langs ['Python', 'HTML', 'CSS', 'C', 'R', 'Lua', 'Java'] <class 'list'>
- langs[0] HTML <class 'str'>
One Language: Java
Food: ['Burger', 'Pizza', 'Ice Cream', 'Brownie,', 'Paratha'] <class 'list'>
Random Food: Pizza

person {'name': 'Edwin Abraham', 'age': 16, 'grade': 11, 'Language': ['Python', 'HTML', 'CSS', 'C', 'R', 'Lua', 'Java'], 'Email': 'edwinab0007@gmail.com'} <class 'dict'>
- person["name"] Edwin Abraham <class 'str'>

List and Dictionary purpose

A Dictionary is used for defining patterns while a List is to have many different variables

To start exploring more deeply into List, Dictionary. and Iteration we can construct a list about food and people.

InfoDb = []

# This is a list about my information and gives a list of this
InfoDb.append({
    "FirstName": "Edwin",
    "LastName": "Abraham",
    "DOB": "August 7",
    "Residence": "San Diego",
    "Email": "edwinab0007@gmail.com",
    "Hobbies": ["Biking","Hiking", "Playing Video Games"],
    "Food": ["Burgers", "Pizza", "Brownies", "Watermelon"]
})

print()
print()

# This is another list about my partner in coding who is Emaad Mir
InfoDb.append({ # This bracket includes everything until the closed bracket
    "FirstName": "Emaad",
    "LastName": "Mir",
    "DOB": "January 12",
    "Residence": "San Diego",
    "Email": "emaadidrismir@gmail.com",
    "Hobbies": ["Playing Squash", "Sleeping", "Hiking", "Cooking", "Playing Basketball"],
    "Food": ["French Fries", "Ice Cream", "Bananas", "Pizza"],
})

# Prints the data structure
print(InfoDb)

[{'FirstName': 'Edwin', 'LastName': 'Abraham', 'DOB': 'August 7', 'Residence': 'San Diego', 'Email': 'edwinab0007@gmail.com', 'Hobbies': ['Biking', 'Hiking', 'Playing Video Games'], 'Food': ['Burgers', 'Pizza', 'Brownies', 'Watermelon']}, {'FirstName': 'Emaad', 'LastName': 'Mir', 'DOB': 'January 12', 'Residence': 'San Diego', 'Email': 'emaadidrismir@gmail.com', 'Hobbies': ['Playing Squash', 'Sleeping', 'Hiking', 'Cooking', 'Playing Basketball'], 'Food': ['French Fries', 'Ice Cream', 'Bananas', 'Pizza']}]
def print_data(person):
    print("Name:", person["FirstName"], person["LastName"])
    print("Birthday:", person["DOB"])
    print("Email:", person["Email"])
    print("Foods:", ", ".join(person["Food"]))
    print("Hobbies:", ", ".join(person["Hobbies"]))
    print()

print_data(InfoDb[0]) #This prints the variable with information from my data
print_data(InfoDb[1]) #This prints the code and the data from the previous lines from Emaad's data
Name: Edwin Abraham
Birthday: August 7
Email: edwinab0007@gmail.com
Foods: Burgers, Pizza, Brownies, Watermelon
Hobbies: Biking, Hiking, Playing Video Games

Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
Foods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

Using a For Loop

We will use the data and variables that are already in the notebook and just use the variable to print the list

def for_loop():
    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\n")
for_loop()
print("Indexed For Loop Output\n")
for_loop_with_index()
Regular For Loop

Name: Edwin Abraham
Birthday: August 7
Email: edwinab0007@gmail.com
Foods: Burgers, Pizza, Brownies, Watermelon
Hobbies: Biking, Hiking, Playing Video Games

Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
Foods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

Indexed For Loop Output

Name: Edwin Abraham
Birthday: August 7
Email: edwinab0007@gmail.com
Foods: Burgers, Pizza, Brownies, Watermelon
Hobbies: Biking, Hiking, Playing Video Games

Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
Foods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

Using a 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()
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

Name: Edwin Abraham
Birthday: August 7
Email: edwinab0007@gmail.com
Foods: Burgers, Pizza, Brownies, Watermelon
Hobbies: Biking, Hiking, Playing Video Games

Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
Foods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

Using a Recursive Loop

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_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

Name: Edwin Abraham
Birthday: August 7
Email: edwinab0007@gmail.com
Foods: Burgers, Pizza, Brownies, Watermelon
Hobbies: Biking, Hiking, Playing Video Games

Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
Foods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

Time for a Quiz!

Special Thanks to Emaad and Jishnu for helping me develop this quiz!

This Quiz will have multiple lists with multiple subjects while using a for loop to make sure the user has got the question correct.

import getpass

Topic = ["Computer Science Principles", "Trivia", "Technology"]

Quiz = []

Quiz.append({
    "When using [], what are you using?" : "Lists",
    "Does .append allow you to add to a list? (T/F)" : "T",
    "What file can you find the remote_theme and change it?" : "config.yml",
})

Quiz.append({
    "What percent of people live in the northern hemisphere" : "90%",
})

Quiz.append ({
    "What day is the Apple Far Out Event (mm-dd-yyyy)" : "09-07-2022",
})

def question_with_response(prompt):
    print("Question " + ": " + prompt)
    msg = input()
    return msg

def for_loop_index():
    score = [0, 0, 0]
    s = 0
    for topic in Quiz:
        print("\ntopic: " + Topic[s])
        for ques, ans in topic.items():
            rsp = question_with_response(ques)
            if rsp == ans:
                print("Correct! You gain one point")
                score[s] += 1
            else:
                print("Incorrect. This was the wrong answer, your score is the same")
        s += 1
    print()
    print("Score in " + Topic[0] + ": " + str(score[0]) + " out of " + str(len(Quiz[0])))
    print("Score in " + Topic[1] + ": " + str(score[1]) + " out of " + str(len(Quiz[1])))
    print("Score in " + Topic[2] + ": " + str(score[2]) + " out of " + str(len(Quiz[2])))
    return

print('Hello, ' + getpass.getuser() + " this is a quiz with 3 topics and 5 questions")
print("The First Topic is about Computer Science and then 1 question about Trivia and another about Technology")
for_loop_index()
Hello, sunny this is a quiz with 3 topics and 5 questions
The First Topic is about Computer Science and then 1 question about Trivia and another about Technology

topic: Computer Science Principles
Question : When using [], what are you using?
Incorrect. This was the wrong answer, your score is the same
Question : Does .append allow you to add to a list? (T/F)
Correct! You gain one point
Question : What file can you find the remote_theme and change it?
Correct! You gain one point

topic: Trivia
Question : What percent of people live in the northern hemisphere
Correct! You gain one point

topic: Technology
Question : What day is the Apple Far Out Event (mm-dd-yyyy)
Correct! You gain one point

Score in Computer Science Principles: 2 out of 3
Score in Trivia: 1 out of 1
Score in Technology: 1 out of 1