Lists, Dictionaries, Iteration

An introduction to Data Abstraction using Python Lists [] and Python Dictionaries {}.

  • title:Lists, Dictionaries, Iteration- toc: true
  • categories: [units]
  • permalink: /collegeboard/python_lists
  • image: /images/python_lists.png
  • categories: [collegeboard]
  • tags: [python]

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.

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()
# variable of type string
name = "Nathaniel Capule"
print("name", name, type(name))

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

# variable of type float
score = 91.4
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 Nathaniel Capule <class 'str'>
age 16 <class 'int'>
score 91.4 <class 'float'>

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

person {'name': 'Nathaniel Capule', 'age': 16, 'score': 91.4, 'langs': ['Python', 'JavaScript', 'Java', 'Bash']} <class 'dict'>
- person["name"] Nathaniel Capule <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 = []

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)

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Nathaniel",
    "LastName": "Capule",
    "DOB": "July 8",
    "Residence": "Del Sur",
    "Email": "nathancapule13@gmail.com",
    "Owns_Cars": ["2008 BMW 328i"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Toby",
    "LastName": "Leeder",
    "DOB": "March 10",
    "Residence": "4s Ranch",
    "Email": "tobyzeavleeder@gmail.com",
    "Owns_Cars": ["None"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Gene",
    "LastName": "Chang",
    "DOB": "February 19",
    "Residence": "Del Sur",
    "Email": "genechang0219@gmail.com",
    "Owns_Cars": ["None"]
})

# Print the data structure


# print function: given a dictionary of 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()

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

def Backwards_while_loop():
    print("We goin back in time\n")
    i = 4
    while 0 <= i < len(InfoDb):
        record = InfoDb[i]
        print_data(record)
        i -= 1
    return

while_loop()
Recursive loop output

While loop output

Nathaniel Capule
	 Residence: Del Sur
	 Birth Day: July 8
	 Cars: 2008 BMW 328i

Toby Leeder
	 Residence: 4s Ranch
	 Birth Day: March 10
	 Cars: None

Gene Chang
	 Residence: Del Sur
	 Birth Day: February 19
	 Cars: None

While loop output

Nathaniel Capule
	 Residence: Del Sur
	 Birth Day: July 8
	 Cars: 2008 BMW 328i

Toby Leeder
	 Residence: 4s Ranch
	 Birth Day: March 10
	 Cars: None

Gene Chang
	 Residence: Del Sur
	 Birth Day: February 19
	 Cars: None

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)

for_loop()
For loop output

Nathaniel Capule
	 Residence: Del Sur
	 Birth Day: July 8
	 Cars: 2008 BMW 328i

Toby Leeder
	 Residence: 4s Ranch
	 Birth Day: March 10
	 Cars: None

Gene Chang
	 Residence: Del Sur
	 Birth Day: February 19
	 Cars: None

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

Nathaniel Capule
	 Residence: Del Sur
	 Birth Day: July 8
	 Cars: 2008 BMW 328i

Toby Leeder
	 Residence: 4s Ranch
	 Birth Day: March 10
	 Cars: None

Gene Chang
	 Residence: Del Sur
	 Birth Day: February 19
	 Cars: None

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

Nathaniel Capule
	 Residence: Del Sur
	 Birth Day: July 8
	 Cars: 2008 BMW 328i

Toby Leeder
	 Residence: 4s Ranch
	 Birth Day: March 10
	 Cars: None

Gene Chang
	 Residence: Del Sur
	 Birth Day: February 19
	 Cars: None

Q = 5
score=0

def quiz_question(prompt, answer):
    print("Question: " + prompt)
    user_input = input()
    print("Your answer: " + user_input)
    
    if answer == user_input:
        print(user_input + " is correct!")
        global score
        score +=2
    else:
        print ("Your answer:" + user_input + "was incorrect")
        score -=1
    return user_input

q_0 = quiz_question("How many tacos should you eat in a meal?", "3")
q_1 = quiz_question("What class do I have 3rd period?", "APCSP")
q_2 = quiz_question("What is 4 plus 3?", "7")
q_3 = quiz_question("Who?", "Asked")
q_4 = quiz_question("How old is Nathan C?", "16")

if score > 6:
    print(" Congrats, you scored a(n) " + str(score) + ", thats pretty good!")
else:
    print(" You scored a(n) " + str(score) + ", better luck next time.")
Question: How many tacos should you eat in a meal?
Your answer: 3
3 is correct!
Question: What class do I have 3rd period?
Your answer: apcalc
Your answer:apcalcwas incorrect
Question: What is 4 plus 3?
Your answer: 7
7 is correct!
Question: Who?
Your answer: Asked
Asked is correct!
Question: How old is Nathan C?
Your answer: 16
16 is correct!
 Congrats, you scored a(n) 7, thats pretty good!