Lists, Dictionaries, Iteration
An introduction to Data Abstraction using Python Lists [] and Python Dictionaries {}.
- Lists and Dictionaries
- List and Dictionary purpose
- Formatted output of List/Dictionary - for loop
- Alternate methods for iteration - while loop
- Calling a function repeatedly - recursion
- Quiz using List of Dictionaries
- Reversing Data Output Order
- Hacks
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.
- 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.
# variable of type string
name = "Shreya Sapkal" # name is the key/variable, and "john doe" is the value
print("name", name, type(name)) # type(name) is an abbreviation for a string of code
# variable of type integer
age = 17 # integer variable = integers and whole numbers
print("age", age, type(age))
# variable of type float
score = 97.0 # float = more complicated numbers where you have decimal points
print("score", score, type(score))
print()
# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "Bash"] # making a list of items & separating them with commas
print("langs", langs, type(langs))
print("- langs[0]", langs[0], type(langs[0])) # index in the list: change the number in the [] here to produce a different element in the list; 0 = 1st element, 1 = 2nd element, etc.
print()
# variable of type dictionary (a group of keys and values)
person = {
"name": name, # key on the left, values on the right are the values that are going to be assigned
"age": age,
"score": score,
"langs": langs
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
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 ;).
# Define an empty List called InfoDb
# 1st item is always 0; python is a zero index language
# DICTIONARIES use keys and values to store data
# make sure each key has a unique name
InfoDb = []
# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "Shreya",
"LastName": "Sapkal",
"Nicknames": ["Rey", "Reyu", "Shweya"],
"DOB": "December 12",
"Residence": "San Diego",
"Email": "shreya.sapkal959@gmail.com",
"Owns_Cars": ["2013-Ford Escape", "2020-Chrysler Pacifica"],
"Hobbies": ["Karate", "Tennis", "Reading", "Writing", "Drawing"]
})
InfoDb.append({
"FirstName": "Jiya",
"LastName": "Savlani",
"Nicknames": ["Jiyu"],
"DOB": "March 7",
"Residence": "San Diego",
"Email": "starjiyu@gmail.com",
"Owns_Cars": ["Lambo", "Miata"],
"Hobbies": ["Reading", "Watching Cobra Kai"]
})
InfoDb.append({
"FirstName": "Vaishavi",
"LastName": "Jayashankar",
"Nicknames": ["Vaishavi-Chan", "Vai", "Vaiu"],
"DOB": "March 15",
"Residence": "San Diego",
"Email": "vaishavi2005@gmail.com",
"Owns_Cars": ["Volkswagen", "Chevrolet Traverse"],
"Hobbies": ["Music", "Drawing"]
})
# Print the data structure
print(InfoDb)
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.
# 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", "Nicknames: ", end="")
print(", ".join(d_rec["Nicknames"])) # join allows printing a string list with separator
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", "Hobbies: ", end="") # end="" make sure no return occurs
print(", ".join(d_rec["Hobbies"])) # 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()
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()
# my work: changed variable name
def while_loop():
print("While loop output\n")
n = 0
while n < len(InfoDb):
record = InfoDb[n]
print_data(record)
n += 1
return
while_loop()
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)
# values will be the correct answers
q1 = """How many cars does Shreya have?
a. 1
b. 2
c. 3
d. none""" # triple quotation marks allows you to write the question string in multiple lines
q2 = """What is Jiya's nickname?
a. Jiyu
b. Jiji
c. Yaya
d. She doesn't have a nickname"""
q3 = """What are some of Shreya's hobbies?
a. karate
b. tennis
c. drawing
d. all of the above"""
q4 = """Where does Shreya live?
a. San Jose
b. San Fransisco
c. San Diego
d. San Clemente"""
q5 = """What is Jiya's favorite TV show?
a. Miraculous Ladybug
b. Cobra Kai
c. Umbrella Academy
d. Unlisted"""
questions = {q1:"b",q2:"a",q3:"d",q4:"c",q5:"b"} # strings are q1, q2, q3, etc, and the values are the correct answers
score = 0
name = input("Please enter your name:")
print("Please enter your name")
print("Hello", name, "welcome to my quiz using a dictionary")
for i in questions: # starting a for loop to print the questions
print(i) # i = key = question and its option
ans = input("enter the answer (a/b/c/d):") # use input function to get a string input
print("\t", "enter answer (a/b/c/d):")
print("\t", ans)
if ans==questions[i]:
print("correct!")
score = score+1
else:
print("incorrect!")
print("Your final score is:",score)
# copy of the list is made; the list isn't sorted in place
def Reverse(lst): # defining variable: lst
new_lst = lst[::-1]
return new_lst
lst = [20, 21, 22, 23, 24, 25, 26]
print(Reverse(lst)) # reverse key
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.