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.

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))
Name: Emaad Mir <class 'str'>
Age: 15 <class 'int'>
Grade: 105.9 <class 'float'>
Favorite Song: Running Up That Hill <class 'str'>

Random Language: JavaScript
Random Game: Subway Surfer

Name:Emaad Mir Age:15 Grade:105.9 Languages:['Python', 'Html', 'CSS', 'C', 'Java', 'JavaScript', 'C', 'R'] Favorite Song:Running Up That Hill

Reversed List:
Noodles, Fried Rice, Salad, Chocolate Cake, Burgers, Pizza, Bread

Random Order:
Pizza, Burgers, Chocolate Cake, Fried Rice, Noodles, Bread, Salad

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)
[{'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']}, {'FirstName': 'Edwin', 'LastName': 'Abraham', 'DOB': 'August 7', 'Email': 'edwinab0007@gmail.com', 'FavoriteFoods': ['Burgers, Pizza, Brownies, Watermelon'], 'Hobbies': ['Biking', 'Hiking', 'Playing Video Games']}]

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)
Name: Emaad Mir
Birthday: January 12
Email: emaadidrismir@gmail.com
FavoriteFoods: French Fries, Ice Cream, Bananas, Pizza
Hobbies: Playing Squash, Sleeping, Hiking, Cooking, Playing Basketball

For Loops

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()
REGULAR FOR LOOP OUTPUT

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

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

FOR LOOP WITH INDEX OUTPUT

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

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

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()
REGULAR WHILE LOOP

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

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

REVERSED WHILE LOOP

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

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

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
RECURSIVE INDEX OUTPUT

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

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

Adding Records to a Dictionary With User Input

You can also have a user input something so that they can add it to the dictionary. For example, the function below shows a user inputting a student's full name and their grade level, which, once printed, will display what the details of that student.

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)
{'Emaad Mir': '10th'}

Quiz that Stores Dictionaries

Last week, we were all assigned to create a Python quiz. This week, we also need to make a quiz, but it needs to store dictionaries. Below is a demonstration of how that works:

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
    
Hello, root running /bin/python3
You will be asked 6 questions.
Question: Are you ready to take a test?
You said yes, so let's get started!
What syntax allows you to format and pass variables in html?
liquid is correct! Great job!
What is the instructions for what you want a computer to do called?
input is correct! Great job!
What is the name of the theme that your webpage has by default?
minima is correct! Great job!
_______ involves calling itself repeatedly in order to achieve looping
recursion is correct! Great job!
Lists and ________ are used to collect information
dictionaries is correct! Great job!
What is the name of the file that the style directory is stored in (just the name, don't need the type of file)?
sass is correct! Great job!
root, you scored 6/6, which is 100.0%