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
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"]
})

# Append to list a 3rd Dictionary of key/values
InfoDb.append({
    "FirstName": "Joselyn Elise",
    "LastName": "Anda",
    "DOB": "January 15 2006",
    "Residence": "Escondido",
    "Email": "joselynanda@gmail.com",
    "Owns_Cars": ["4Runner", "ToyotaCamry", "Escalade", "Civic"]
})
# 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': 'Joselyn Elise', 'LastName': 'Anda', 'DOB': 'January 15 2006', 'Residence': 'Escondido', 'Email': 'joselynanda@gmail.com', 'Owns_Cars': ['4Runner', 'ToyotaCamry', 'Escalade', 'Civic']}]

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.
InfoDb = []

# given and index this will print InfoDb content
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)

for_loop()
For loop output

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

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

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.

Survey for Dog Owners

Survey/Quiz that stores in list/dictionaries

import getpass, sys
from tkinter import Y

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

questions = 9
correct = 0

print('Hi, ' + getpass.getuser() + ' how are you?')
print("This is a survey with about your dog(s) with " + str(questions) + " questions.")
question_and_answer("Are you ready to take this survey?")

rsp = question_with_response("What is your name?")
print("Hi " + rsp + " nice to meet you :)")

rsp = question_with_response("Do you have a dog?")
print(" Me too! ")

rsp = question_with_response("Is/are your dog(s) a boy or a girl?")
print(" Oh " + rsp + "  Cool, I have 2 girls ")

rsp = question_with_response("What is his/her name?") 
print(rsp + " is a cute name ")
   

rsp = question_with_response("What breed is/are your dog(s)?")
print (" Oooo " + rsp +  " interesting ")
   
    
rsp = question_with_response("What is/are your dog(s) birthday?")
print (" Great ")
   
rsp = question_with_response("What is the color of their collar?")
print (rsp + " is a nice color ")

rsp = question_with_response("What are your dog(s) favorite treats?")
print ( " Oh cool, mine too! ")

rsp = question_with_response("Lastly, what are your dog(s) favorite hobbies?")
print ( " Haha fun ")

print(" Okay, " + getpass.getuser() + " thank you so much for taking this survey! Down below is some facts about my dogs." )
Hi, jesa how are you?
This is a survey with about your dog(s) with 9 questions.
Question: Are you ready to take this survey?
Answer: yes
Question: What is your name?
Hi DeeBo nice to meet you :)
Question: Do you have a dog?
 Me too! 
Question: Is/are your dog(s) a boy or a girl?
 Oh females  Cool, I have 2 girls 
Question: What is his/her name?
Nikki & Lekkili is a cute name 
Question: What breed is/are your dog(s)?
 Oooo Rottie/Dobie/German Mix & Full Rottie interesting 
Question: What is/are your dog(s) birthday?
 Great 
Question: What is the color of their collar?
blood is a nice color 
Question: What are your dog(s) favorite treats?
 Oh cool, mine too! 
Question: Lastly, what are your dog(s) favorite hobbies?
 Haha fun 
 Okay, jesa thank you so much for taking this survey! Down below is some facts about my dogs.

Hacks

Adding records in my List

InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "Name": "Elly",
    "DogBreed": "Rottweiler",
    "DOB": "January 18 2010",
    "Residence": "Escondido",
    "FavoriteColor": "Red",
    "FavoriteHobbies": ["Sleeping", "Eating", "Playing"], 
    "Weight": "96.7 pounds"

})


# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "Name": "Athyna",
    "DogBreed": "Pitbull",
    "DOB": "April 25 2012",
    "Residence": "Escondido",
    "FavoriteColor": "Purple",
    "FavoriteHobbies": ["Sleeping","Chasing animals", "Playing" ], 
    "Weight": "45.5 pounds"

})

# Print the data structure
print(InfoDb)
[{'Name': 'Elly', 'DogBreed': 'Rottweiler', 'DOB': 'January 18 2010', 'Residence': 'Escondido', 'FavoriteColor': 'Red', 'FavoriteHobbies': ['Sleeping', 'Eating', 'Playing'], 'Weight': '96.7 pounds'}, {'Name': 'Athyna', 'DogBreed': 'Pitbull', 'DOB': 'April 25 2012', 'Residence': 'Escondido', 'FavoriteColor': 'Purple', 'FavoriteHobbies': ['Sleeping', 'Chasing animals', 'Playing'], 'Weight': '45.5 pounds'}]

Hacks cont...

For loop without index

InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "Name": "Elly",
    "DogBreed": "Rottweiler",
    "DOB": "January 18 2010",
    "Residence": "Escondido",
    "FavoriteColor": "Red",
    "FavoriteHobbies": ["Sleeping", "Eating", "Playing"], 
    "Weight": "96.7 pounds"

})


# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "Name": "Athyna",
    "DogBreed": "Pitbull",
    "DOB": "April 25 2012",
    "Residence": "Escondido",
    "FavoriteColor": "Purple",
    "FavoriteHobbies": ["Sleeping","Chasing animals", "Playing" ], 
    "Weight": "45.5 pounds"

})

# Print the data structure
print(InfoDb)# given and index this will print InfoDb content
def print_data(d_rec):
    print("\t", d_rec["Name"])  # 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", "Favorite Color:", d_rec["FavoriteColor"])
    print("\t", "Favorite Hobbies:", d_rec["FavoriteHobbies"])
    print("\t", "Weight: ", end="")  # end="" make sure no return occurs
    print("".join(d_rec["Weight"]))  # join allows printing a string list with separator
    print() 

def for_loop():
    print("My Dogs Info\n")
    for record in InfoDb:
        print_data(record)

for_loop()
[{'Name': 'Elly', 'DogBreed': 'Rottweiler', 'DOB': 'January 18 2010', 'Residence': 'Escondido', 'FavoriteColor': 'Red', 'FavoriteHobbies': ['Sleeping', 'Eating', 'Playing'], 'Weight': '96.7 pounds'}, {'Name': 'Athyna', 'DogBreed': 'Pitbull', 'DOB': 'April 25 2012', 'Residence': 'Escondido', 'FavoriteColor': 'Purple', 'FavoriteHobbies': ['Sleeping', 'Chasing animals', 'Playing'], 'Weight': '45.5 pounds'}]
My Dogs Info

	 Elly
	 Residence: Escondido
	 Birth Day: January 18 2010
	 Favorite Color: Red
	 Favorite Hobbies: ['Sleeping', 'Eating', 'Playing']
	 Weight: 96.7 pounds

	 Athyna
	 Residence: Escondido
	 Birth Day: April 25 2012
	 Favorite Color: Purple
	 Favorite Hobbies: ['Sleeping', 'Chasing animals', 'Playing']
	 Weight: 45.5 pounds

InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "Name": "Elly",
    "DogBreed": "Rottweiler",
    "DOB": "January 18 2010",
    "Residence": "Escondido",
    "FavoriteColor": "Red",
    "FavoriteHobbies": ["Sleeping", "Eating", "Playing"], 
    "Weight": "96.7 pounds"

})


# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "Name": "Athyna",
    "DogBreed": "Pitbull",
    "DOB": "April 25 2012",
    "Residence": "Escondido",
    "FavoriteColor": "Purple",
    "FavoriteHobbies": ["Sleeping","Chasing animals", "Playing" ], 
    "Weight": "45.5 pounds"

})

# Print the data structure
print(InfoDb)# given and index this will print InfoDb content
def print_data(d_rec):
    print("\t", d_rec["Name"])  # 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", "Favorite Color:", d_rec["FavoriteColor"])
    print("\t", "Favorite Hobbies:", d_rec["FavoriteHobbies"])
    print("\t", "Weight: ", end="")  # end="" make sure no return occurs
    print("".join(d_rec["Weight"]))  # join allows printing a string list with separator
    print() 

def for_loop():
    print("My Dogs Info\n")
    # print(range(len(InfoDb)))
    # print(len(InfoDb))
    for index in range(len(InfoDb)):
        print_data(InfoDb[index])

for_loop()
[{'Name': 'Elly', 'DogBreed': 'Rottweiler', 'DOB': 'January 18 2010', 'Residence': 'Escondido', 'FavoriteColor': 'Red', 'FavoriteHobbies': ['Sleeping', 'Eating', 'Playing'], 'Weight': '96.7 pounds'}, {'Name': 'Athyna', 'DogBreed': 'Pitbull', 'DOB': 'April 25 2012', 'Residence': 'Escondido', 'FavoriteColor': 'Purple', 'FavoriteHobbies': ['Sleeping', 'Chasing animals', 'Playing'], 'Weight': '45.5 pounds'}]
My Dogs Info

	 Elly
	 Residence: Escondido
	 Birth Day: January 18 2010
	 Favorite Color: Red
	 Favorite Hobbies: ['Sleeping', 'Eating', 'Playing']
	 Weight: 96.7 pounds

	 Athyna
	 Residence: Escondido
	 Birth Day: April 25 2012
	 Favorite Color: Purple
	 Favorite Hobbies: ['Sleeping', 'Chasing animals', 'Playing']
	 Weight: 45.5 pounds

Hacks cont...

Playing with index in for loop, if I change index to 0, it will only loop my first record, which is information about Elly.

InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "Name": "Elly",
    "DogBreed": "Rottweiler",
    "DOB": "January 18 2010",
    "Residence": "Escondido",
    "FavoriteColor": "Red",
    "FavoriteHobbies": ["Sleeping", "Eating", "Playing"], 
    "Weight": "96.7 pounds"

})


# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "Name": "Athyna",
    "DogBreed": "Pitbull",
    "DOB": "April 25 2012",
    "Residence": "Escondido",
    "FavoriteColor": "Purple",
    "FavoriteHobbies": ["Sleeping","Chasing animals", "Playing" ], 
    "Weight": "45.5 pounds"

})

# Print the data structure
print(InfoDb)# given and index this will print InfoDb content
def print_data(d_rec):
    print("\t", d_rec["Name"])  # 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", "Favorite Color:", d_rec["FavoriteColor"])
    print("\t", "Favorite Hobbies:", d_rec["FavoriteHobbies"])
    print("\t", "Weight: ", end="")  # end="" make sure no return occurs
    print("".join(d_rec["Weight"]))  # join allows printing a string list with separator
    print() 

def for_loop():
    print("My Dogs Info\n")
    # print(range(len(InfoDb)))
    # print(len(InfoDb))
    for index in range(len(InfoDb)):
        print_data(InfoDb[0])

for_loop()
[{'Name': 'Elly', 'DogBreed': 'Rottweiler', 'DOB': 'January 18 2010', 'Residence': 'Escondido', 'FavoriteColor': 'Red', 'FavoriteHobbies': ['Sleeping', 'Eating', 'Playing'], 'Weight': '96.7 pounds'}, {'Name': 'Athyna', 'DogBreed': 'Pitbull', 'DOB': 'April 25 2012', 'Residence': 'Escondido', 'FavoriteColor': 'Purple', 'FavoriteHobbies': ['Sleeping', 'Chasing animals', 'Playing'], 'Weight': '45.5 pounds'}]
My Dogs Info

	 Elly
	 Residence: Escondido
	 Birth Day: January 18 2010
	 Favorite Color: Red
	 Favorite Hobbies: ['Sleeping', 'Eating', 'Playing']
	 Weight: 96.7 pounds

	 Elly
	 Residence: Escondido
	 Birth Day: January 18 2010
	 Favorite Color: Red
	 Favorite Hobbies: ['Sleeping', 'Eating', 'Playing']
	 Weight: 96.7 pounds

Hacks cont...

If I change the index to 1, it will loop the second record, about Athyna. I can also put in a code in the for loop for it to tell me the range and legnth of index.

# Prints 'Range'
print(range(len(InfoDb)))
# Prints 'Length of Index in InfoDb'
print(len(InfoDb))
  • Make sure to place this information/code indented under def for_loop(), so it knows to be run under/in the for loop and with the InfoDb data
InfoDb = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "Name": "Elly",
    "DogBreed": "Rottweiler",
    "DOB": "January 18 2010",
    "Residence": "Escondido",
    "FavoriteColor": "Red",
    "FavoriteHobbies": ["Sleeping", "Eating", "Playing"], 
    "Weight": "96.7 pounds"

})


# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "Name": "Athyna",
    "DogBreed": "Pitbull",
    "DOB": "April 25 2012",
    "Residence": "Escondido",
    "FavoriteColor": "Purple",
    "FavoriteHobbies": ["Sleeping","Chasing animals", "Playing" ], 
    "Weight": "45.5 pounds"

})

# Print the data structure
print(InfoDb)# given and index this will print InfoDb content
def print_data(d_rec):
    print("\t", d_rec["Name"])  # 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", "Favorite Color:", d_rec["FavoriteColor"])
    print("\t", "Favorite Hobbies:", d_rec["FavoriteHobbies"])
    print("\t", "Weight: ", end="")  # end="" make sure no return occurs
    print("".join(d_rec["Weight"]))  # join allows printing a string list with separator
    print() 

def for_loop():
    print("My Dogs Info\n")
    print(range(len(InfoDb)))
    print(len(InfoDb))
    for index in range(len(InfoDb)):
        print_data(InfoDb[1])

for_loop()
[{'Name': 'Elly', 'DogBreed': 'Rottweiler', 'DOB': 'January 18 2010', 'Residence': 'Escondido', 'FavoriteColor': 'Red', 'FavoriteHobbies': ['Sleeping', 'Eating', 'Playing'], 'Weight': '96.7 pounds'}, {'Name': 'Athyna', 'DogBreed': 'Pitbull', 'DOB': 'April 25 2012', 'Residence': 'Escondido', 'FavoriteColor': 'Purple', 'FavoriteHobbies': ['Sleeping', 'Chasing animals', 'Playing'], 'Weight': '45.5 pounds'}]
My Dogs Info

range(0, 2)
2
	 Athyna
	 Residence: Escondido
	 Birth Day: April 25 2012
	 Favorite Color: Purple
	 Favorite Hobbies: ['Sleeping', 'Chasing animals', 'Playing']
	 Weight: 45.5 pounds

	 Athyna
	 Residence: Escondido
	 Birth Day: April 25 2012
	 Favorite Color: Purple
	 Favorite Hobbies: ['Sleeping', 'Chasing animals', 'Playing']
	 Weight: 45.5 pounds