Lists and Dictionaries

As a quick review we used variables in the introduction last week. 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.

  1. 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.
  2. Take a minute and see if you can reference other elements in the list or other keys in the dictionary. Show output.
# variable of type string
name = "John Doe"
print("name", name, type(name))

# variable of type integer
age = 18
print("age", age, type(age))

# variable of type float
score = 90.0
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "Bash"]
print("langs", langs, type(langs))
print("- langs[3]", langs[3], type(langs[3]))

print()

# variable of type dictionary (a group of keys and values)
person = {
    "name": name,
    "age": age,
    "score": score,
    "langs": langs
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
name John Doe <class 'str'>
age 18 <class 'int'>
score 90.0 <class 'float'>

langs ['Python', 'JavaScript', 'Java', 'Bash'] <class 'list'>
- langs[3] Bash <class 'str'>

person {'name': 'John Doe', 'age': 18, 'score': 90.0, 'langs': ['Python', 'JavaScript', 'Java', 'Bash']} <class 'dict'>
- person["name"] John Doe <class 'str'>

List and Dictionary purpose

Our society is being build on information. List and Dictionaries are used to collect information. Mostly, when information is collected it is formed into patterns. As that pattern is established you will collect many instances of that pattern.

  • List is used to collect many
  • 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 we will explore constructing a List of people and cars.

  • As we learned above, List is a data type: class 'list'
  • A 'list' data type has the method '.append(expression)' that allows you to add to the list
  • In the example below, the expression 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. The output looks similar to JSON and we will see this often, you will be required to understand this data structure and understand the parts. Easy peasy ;).
InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Keira",
    "LastName": "Okimoto",
    "DOB": "December 21",
    "Residence": "San Diego",
    "Email": "keiraokimoto@gmail.com",
    "Owns_Cars": ["None"],
    "Owns_Cheese": "None",
    "Hobbies": ["Swimming", "Drawing", "Playing games", "Sleeping"],
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "George",
    "LastName": "Washington",
    "DOB": "May 12",
    "Residence": "Some cemetary somewhere",
    "Email": "georgewashington@gmail.com",
    "Owns_Cars": ["None"],
    "Owns_Cheese": "Parmasan",
    "Hobbies": ["Swimming", "Horseback riding", "Hunting"],
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'Keira', 'LastName': 'Okimoto', 'DOB': 'December 21', 'Residence': 'San Diego', 'Email': 'keiraokimoto@gmail.com', 'Owns_Cars': ['None'], 'Owns_Cheese': 'None', 'Hobbies': ['Swimming', 'Drawing', 'Playing games', 'Sleeping']}, {'FirstName': 'George', 'LastName': 'Washington', 'DOB': 'May 12', 'Residence': 'Some cemetary somewhere', 'Email': 'georgewashington@gmail.com', 'Owns_Cars': ['None'], 'Owns_Cheese': 'Parmasan', 'Hobbies': ['Swimming', 'Horseback riding', 'Hunting']}]

Formatted output of List/Dictionary - for loop

Managing data in Lists and Dictionaries is for the convenience of passing the data across the internet or preparing it to be stored into a database. Also, it is a great way to exchange data inside of our own programs.

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(d_rec):
    print(d_rec["FirstName"], d_rec["LastName"])  # using comma puts space between values
    print("\t", "Residence:", d_rec["Residence"]) # \t is a tab indent
    print("\t", "Birth Day:", d_rec["DOB"])
    print("\t", "Cars: ", end="")  # end="" make sure no return occurs
    print(", ".join(d_rec["Owns_Cars"]))  # join allows printing a string list with separator
    print("\t", "Cheese: ", d_rec["Owns_Cheese"])
    print("\t", "Hobbies:", end="")
    print(", ".join(d_rec["Hobbies"]))
    print()


# for loop 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

Keira Okimoto
	 Residence: San Diego
	 Birth Day: December 21
	 Cars: None
	 Cheese:  None
	 Hobbies:Swimming, Drawing, Playing games, Sleeping

George Washington
	 Residence: Some cemetary somewhere
	 Birth Day: May 12
	 Cars: None
	 Cheese:  Parmasan
	 Hobbies:Swimming, Horseback riding, Hunting

Alternate methods for iteration - 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

Keira Okimoto
	 Residence: San Diego
	 Birth Day: December 21
	 Cars: None
	 Cheese:  None
	 Hobbies:Swimming, Drawing, Playing games, Sleeping

George Washington
	 Residence: Some cemetary somewhere
	 Birth Day: May 12
	 Cars: None
	 Cheese:  Parmasan
	 Hobbies:Swimming, Horseback riding, Hunting

Calling a function repeatedly - recursion

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

Keira Okimoto
	 Residence: San Diego
	 Birth Day: December 21
	 Cars: None
	 Cheese:  None
	 Hobbies:Swimming, Drawing, Playing games, Sleeping

George Washington
	 Residence: Some cemetary somewhere
	 Birth Day: May 12
	 Cars: None
	 Cheese:  Parmasan
	 Hobbies:Swimming, Horseback riding, Hunting


List Loops

Yeet variable is a list of strings, storing random words. The while loop is used to iterate through the list. Each item in the list is printed in the order added. The index is started at 0 and increment by 1 for each time.

yeet = ["woo", "wee", "hee", "hoo", "yee", "yoo"]

# while loop contains an initial n and an index incrementing statement (n += 1)
def while_loop():
    print("While loop output\n")
    
    i = 0
    while i < len(yeet):
        print(yeet[i])
        i += 1
    return

while_loop()
While loop output

woo
wee
hee
hoo
yee
yoo

For Loop for Lists

For a For Loop, the name of the list is defined and placed into the code. It is defined as d_yeet.

def print_data(d_yeet):
    print(d_yeet)

def for_loop():
    print("For loop output\n")
    for record in yeet:
        print_data(record)
for_loop()

# Prints data in the d_yeet list
For loop output

woo
wee
hee
hoo
yee
yoo

Reverse Loop for Lists

For the reversed list, the code is defined the same as the original loop, but the reverse command is added to reverse the list.

yeet = ["woo", "wee", "hee", "hoo", "yee", "yoo"]
#yeet is the variable and it is equal to the string

def print_data(d_yeet):
    print(d_yeet)

#'d_yeet' is used to replace the name 'yeet' as a definition

def reverse_for_loop():
    print ("Reverse for loop using reversed\n")
    for record in reversed(yeet):
        print_data(record)
reverse_for_loop() 

#reversed command reverses the list

def reverse_for_loop_2():
    print ("Reverse for loop using range\n")
    for index in range(len(yeet) -1, -1, -1):
        print_data(yeet[index ])
reverse_for_loop_2()  

#reversing the data using a range - 'len' = the length. -1 subtracts from the list/makes it reverse
Reverse for loop using reversed

yoo
yee
hoo
hee
wee
woo
Reverse for loop using range

yoo
yee
hoo
hee
wee
woo

Recursive Loop for Lists

For a recursive loop with a list, the list name is added to the code.

yeet = ["woo", "wee", "hee", "hoo", "yee", "yoo"]

# recursive loop essentially continues endlessly until the exit condition is met (which ends at (i + 1))
def recursive_loop(i):
    if i < len(yeet):
        record = yeet[i]
        print_data(record)
        recursive_loop(i + 1)
    return
    
print("Recursive loop output\n")
recursive_loop(0)
Recursive loop output

woo
wee
hee
hoo
yee
yoo

Dictionary/List Quiz

import getpass, sys
EnstarsUnits = ["ALKALOID", "Trickstar", "fine", "Eden", "Knights"]
EnstarsCharacters = ["Hiiro", "Mao", "Wataru", "Nagisa", "Ritsu"]
# Lists (ignore these they aren't used in the code)

Enstars = {
    "ALKALOID": "Hiiro Amagi",
    "Trickstar": "Mao Isara",
    "fine": "Wataru Hibiki",
    "Eden": "Nagisa Ran",
    "Knights": "Ritsu Sakuma",
}
# The dictionary/list dictionary

CorrectList = {}
IncorrectList = {}
# Empty dictionaries used to store data

def question_with_response(unit):
    print("What is your favorite " + unit + " character?")
    msg = input ()
    return msg

# defines and prints question; asks for input

def question():
    for unit in EnstarsUnits:
        rsp = question_with_response(unit)
        if (rsp != Enstars [unit]):
            print (rsp + " is incorrect.")
            IncorrectList [unit] = rsp
        else:
            print (rsp + " is correct.")
            CorrectList [unit] = rsp

# defines unit as one of the keys in the dictionary
# answers are marked as incorrect if they do not match the values that go with the keys
        
question()
What is your favorite ALKALOID character?
Hiiro Amagi is correct.
What is your favorite Trickstar character?
Mao Isara is correct.
What is your favorite fine character?
Wataru Hibiki is correct.
What is your favorite Eden character?
Nagisa Ran is correct.
What is your favorite Knights character?
Ritsu Sakuma is correct.

Hacks

  • Add a couple of records to the InfoDb
  • Try to do a for loop with an index
  • Pair Share code somethings creative or unique, with loops and data. Hints...
    • Would it be possible to output data in a reverse order?
    • Are there other methods that can be performed on lists?
    • Could you create new or add to dictionary data set? Could you do it with input?
    • Make a quiz that stores in a List of Dictionaries.