Lists and Dictionaries

As a quick review of variables in the introduction last week. String, Integer, Float, List and Dictionary are some of the types of variables. 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)) #string is a primitive

# variable of type integer
age = 18
print("age", age, type(age)) #int is a primitive

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

print()

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java"]
print("langs", langs, type(langs)) #list is a collection
print("- langs[0]", langs[0], type(langs[0])) #element in this list in a primitive

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)) #dictionary is a collection
print('- person["name"]', person["name"], type(person["name"])) #string in dictionary is primitive
name John Doe <class 'str'>
age 18 <class 'int'>
score 90.0 <class 'float'>

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

person {'name': 'John Doe', 'age': 18, 'score': 90.0, 'langs': ['Python', 'JavaScript', 'Java']} <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
InfoDb.append({
    "FirstName": "John",
    "LastName": "Mortensen",
    "DOB": "October 21",
    "Residence": "San Diego",
    "Email": "jmortensen@powayusd.com",
    "Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Sunny",
    "LastName": "Naidu",
    "DOB": "August 2",
    "Residence": "Temecula",
    "Email": "snaidu@powayusd.com",
    "Owns_Cars": ["4Runner"]
})

InfoDb.append({
    "FirstName": "Haoxuan",
    "LastName": "Tong",
    "DOB": "July 9",
    "Residence": "San Diego",
    "Email": "haoxuantong8@gmail.com",
    "Owns_Cars": []
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'John', 'LastName': 'Mortensen', 'DOB': 'October 21', 'Residence': 'San Diego', 'Email': 'jmortensen@powayusd.com', 'Owns_Cars': ['2015-Fusion', '2011-Ranger', '2003-Excursion', '1997-F350', '1969-Cadillac']}, {'FirstName': 'Sunny', 'LastName': 'Naidu', 'DOB': 'August 2', 'Residence': 'Temecula', 'Email': 'snaidu@powayusd.com', 'Owns_Cars': ['4Runner']}, {'FirstName': 'Haoxuan', 'LastName': 'Tong', 'DOB': 'July 9', 'Residence': 'San Diego', 'Email': 'haoxuantong8@gmail.com', 'Owns_Cars': []}]

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


# for loop iterates on length of InfoDb
def for_loop():
    print("For loop output\n")
    for record in InfoDb:
        print_data(record)

InfoDb = []
InfoDb.append({
    "FirstName": "John",
    "LastName": "Mortensen",
    "DOB": "October 21",
    "Residence": "San Diego",
    "Email": "jmortensen@powayusd.com",
    "Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})

InfoDb.append({
    "FirstName": "Sunny",
    "LastName": "Naidu",
    "DOB": "August 2",
    "Residence": "Temecula",
    "Email": "snaidu@powayusd.com",
    "Owns_Cars": ["4Runner"]
})

InfoDb.append({
    "FirstName": "Haoxuan",
    "LastName": "Tong",
    "DOB": "July 9",
    "Residence": "San Diego",
    "Email": "haoxuantong8@gmail.com",
    "Owns_Cars": []
})

for_loop()
For loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

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

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

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

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

Calling a for loop with index

Instead of using elements, using the function range can create a list of indexes to output the data.

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


# for loop iterates on length of InfoDb
def for_loop():
    print("For loop output\n")
    for i in range(len(InfoDb)): #Using range(len(InfoDb)) to create an iterable of indices
        print_data(InfoDb[i])


for_loop()
For loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

Outputting data in reverse

Using range(0,len(InfoDb),-1), we can output the date in reverse.

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


# for loop iterates on length of InfoDb with indices
def for_loop_indices():
    print("Reverse with indices\n")
    for i in range(len(InfoDb)-1,-1,-1): #Using range(len(InfoDb)-1,-1,-1) to create a reversed iterable of indices
        print_data(InfoDb[i])


for_loop_indices()
Reverse with indices

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Poping and Slicing from a List

Using pop() to pop values from selected indices

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


# for loop iterates on length of InfoDb
def for_loop():
    print("For loop output\n")
    for i in range(len(InfoDb)): #Using range(len(InfoDb)) to create an iterable of indices
        print_data(InfoDb[i])


print("pop")
print("Original List\n")
for_loop()#printing the original list
popped=InfoDb.pop(0)#popping the first element from list and storing it in a variable
print("New List\n")
for_loop()#printing the new list
print("Popped Variable\n")
print_data(popped)#printing the popped variable
InfoDb.append(popped)#adding the popped element back into the list
print("")

print("slice")
print("Original List\n")
for_loop()#printing the original list
aSlice=InfoDb[1:3]#slicing the second element and third from list and storing it in a variable
print("New List\n")
for_loop()#printing the new list, it should be the same
print("Slice variables")
print_data(aSlice[0])#printing the first and second variable in the slice
print_data(aSlice[1])
print("")
pop
Original List

For loop output

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

New List

For loop output

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Popped Variable

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner


slice
Original List

For loop output

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

New List

For loop output

Haoxuan Tong
	 Residence: San Diego
	 Birth Day: July 9
	 Cars: 

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner

Slice variables
John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Cars: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Sunny Naidu
	 Residence: Temecula
	 Birth Day: August 2
	 Cars: 4Runner


Adding to a Dictionary with Inputs

Using input to add a value to a dictionary with the key and value.

aDict={
    'a':12,
    'b':34
}#creating a dictionary
print("Original Dictionary")
print(aDict)
key=input("Enter your key (str): ")#get the key
ele=int(input("Enter your element (int): "))#get the element
aDict[key]=ele#adding the element to the dictionary
print("New Dictionary")
print(aDict)#printing the dictionary
Original Dictionary
{'a': 12, 'b': 34}
New Dictionary
{'a': 12, 'b': 34, 'c': 28}

Quiz using Dictionaries

Using Dictionaries to create a quiz

import getpass, sys

def question_with_response(prompt):
    #function for asking and answering
    print("Question: " + prompt)
    msg = input()
    return msg


quizQnA={
    "What folder is used to create markdown posts?":"posts",
    "What folder is used to create notebook posts?":"notebook",
    "What is the term for submitting a change made in editor?":"commit",
    "What command is used to include other functions that are developed?":"import",
    "What command in this example is used to evaluate a response?":"if",
    "Each 'if' command contains an '_________' to determine a true or false condition?":"expression",
}#define the questions

quizLength=len(quizQnA)#measures the length of question
ans=0#add variable for answered correctly

for question in quizQnA:
    resp=question_with_response(question)
    if resp==quizQnA[question]:
        print(resp+" was correct!")
        ans+=1
    else:
        print(resp+" was incorrect.")
        print("The correct answer is "+quizQnA[question])

print(getpass.getuser()+", you scored "+str(ans)+"/"+str(quizLength)+", which is "+str(format(ans/quizLength*100,".2f"))+"%")
Question: What folder is used to create markdown posts?
posts was correct!
Question: What folder is used to create notebook posts?
notebook was correct!
Question: What is the term for submitting a change made in editor?
commit was correct!
Question: What command is used to include other functions that are developed?
commit was incorrect.
The correct answer is import
Question: What command in this example is used to evaluate a response?
if was correct!
Question: Each 'if' command contains an '_________' to determine a true or false condition?
expression was correct!
haoxu, you scored 5/6, which is 83.33%

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.