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 ;).
InfoDb1 = []

# Append to List a Dictionary of key/values related to a person and cars
InfoDb1.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
InfoDb1.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
InfoDb1.append({
    "FirstName": "Samit",
    "LastName": "Poojary",
    "DOB": "February 24",
    "Residence": "San Diego",
    "Email": "samitpoojary@gmail.com",
    "Owns_Cars": ["Pagani Zonda HP Barchetta"]

})

# Append to List a 4th Dictionary of key/values
InfoDb1.append({
    "FirstName": "Harish",
    "LastName": "Poojary",
    "DOB": "December 4",
    "Residence": "San Diego",
    "Email": "hpoojary@gmail.com",
    "Owns_Cars": ["Porsche Cayenne GTS Turbo"]

})

# Print the data structure
print(InfoDb1)
[{'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': 'Samit', 'LastName': 'Poojary', 'DOB': 'February 24', 'Residence': 'San Diego', 'Email': 'samitpoojary@gmail.com', 'Owns_Cars': ['Pagani Zonda HP Barchetta']}, {'FirstName': 'Harish', 'LastName': 'Poojary', 'DOB': 'December 4', 'Residence': 'San Diego', 'Email': 'hpoojary@gmail.com', 'Owns_Cars': ['Porsche Cayenne GTS Turbo']}]

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 InfoDb1:
        print_data(record)

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

Samit Poojary
	 Residence: San Diego
	 Birth Day: February 24
	 Cars: Pagani Zonda HP Barchetta

Harish Poojary
	 Residence: San Diego
	 Birth Day: December 4
	 Cars: Porsche Cayenne GTS Turbo

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(InfoDb1):
        record = InfoDb1[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

Samit Poojary
	 Residence: San Diego
	 Birth Day: February 24
	 Cars: Pagani Zonda HP Barchetta

Harish Poojary
	 Residence: San Diego
	 Birth Day: December 4
	 Cars: Porsche Cayenne GTS Turbo

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(InfoDb1):
        record = InfoDb1[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

Samit Poojary
	 Residence: San Diego
	 Birth Day: February 24
	 Cars: Pagani Zonda HP Barchetta

Harish Poojary
	 Residence: San Diego
	 Birth Day: December 4
	 Cars: Porsche Cayenne GTS Turbo

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.

Adding Extra Records / Entries to a new InfoDb

  • This cell not only defines InfoDb, but also adds extra entries about people and their characteristics
InfoDb2 = []

# InfoDB is a data structure with expected Keys and Values

# Append to List a Dictionary of key/values related to a person and their height
InfoDb2.append({
    "FirstName": "Samit",
    "LastName": "Poojary",
    "DOB": "February 24",
    "Residence": "San Diego",
    "Email": "samit.poojary@gmail.com",
    "Hobbies": ["Soccer, Basketball, Fantasy Basketball"]
})

#adding extra records to InfoDb

InfoDb2.append({
    "FirstName": "Vardaan",
    "LastName": "Sinha",
    "DOB": "September 28",
    "Residence": "San Diego",
    "Email": "vardsin28@gmail.com",
    "Hobbies": ["Coding, Fantasy Football"]
})
# adding extra records
InfoDb2.append({
    "FirstName": "Alex",
    "LastName": "Kumar",
    "DOB": "May 9",
    "Residence": "San Diego",
    "Email": "alex.k.kumar@gmail.com",
    "Hobbies": ["Basketball, Trolling"]
})
# Adding one extra item to InfoDb
InfoDb2.append({
    "FirstName": "Harish",
    "LastName": "Poojary",
    "DOB": "December 4",
    "Residence": "San Diego",
    "Email": "hpoojary@gmail.com",
    "Hobbies": ["Basketball, Hiking"]
})

print(InfoDb2)
[{'FirstName': 'Samit', 'LastName': 'Poojary', 'DOB': 'February 24', 'Residence': 'San Diego', 'Email': 'samit.poojary@gmail.com', 'Hobbies': ['Soccer, Basketball, Fantasy Basketball']}, {'FirstName': 'Vardaan', 'LastName': 'Sinha', 'DOB': 'September 28', 'Residence': 'San Diego', 'Email': 'vardsin28@gmail.com', 'Hobbies': ['Coding, Fantasy Football']}, {'FirstName': 'Alex', 'LastName': 'Kumar', 'DOB': 'May 9', 'Residence': 'San Diego', 'Email': 'alex.k.kumar@gmail.com', 'Hobbies': ['Basketball, Trolling']}, {'FirstName': 'Harish', 'LastName': 'Poojary', 'DOB': 'December 4', 'Residence': 'San Diego', 'Email': 'hpoojary@gmail.com', 'Hobbies': ['Basketball, Hiking']}]

Utilizing a For Loop to print out InfoDb

  • Within this next cell below, we wil witness the efficiency behind the utilization of a for loop, which allows us to print the data of the InfoDb without going through the annoying task of manual input.
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", "Email:", d_rec["Email"])
    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 InfoDb2:
        print_data(record)

for_loop()
For loop output

Samit Poojary
	 Residence: San Diego
	 Birth Day: February 24
	 Email: samit.poojary@gmail.com
	 Hobbies: Soccer, Basketball, Fantasy Basketball

Vardaan Sinha
	 Residence: San Diego
	 Birth Day: September 28
	 Email: vardsin28@gmail.com
	 Hobbies: Coding, Fantasy Football

Alex Kumar
	 Residence: San Diego
	 Birth Day: May 9
	 Email: alex.k.kumar@gmail.com
	 Hobbies: Basketball, Trolling

Harish Poojary
	 Residence: San Diego
	 Birth Day: December 4
	 Email: hpoojary@gmail.com
	 Hobbies: Basketball, Hiking

Here is another way to run a for loop, but with a slightly different syntax:

for i in range(len(InfoDb2)):
    print(InfoDb2[i]["FirstName"], InfoDb2[i]["LastName"], "\n", "\t", "DOB:", InfoDb2[i]["DOB"], "\n", "\t", "Residence:", InfoDb2[i]["Residence"], "\n", "\t", "Email: ", InfoDb2[i]["Email"], "\n", "\t", "Hobbies: " ,InfoDb2[i]["Hobbies"])
Samit Poojary 
 	 DOB: February 24 
 	 Residence: San Diego 
 	 Email:  samit.poojary@gmail.com 
 	 Hobbies:  ['Soccer, Basketball, Fantasy Basketball']
Vardaan Sinha 
 	 DOB: September 28 
 	 Residence: San Diego 
 	 Email:  vardsin28@gmail.com 
 	 Hobbies:  ['Coding, Fantasy Football']
Alex Kumar 
 	 DOB: May 9 
 	 Residence: San Diego 
 	 Email:  alex.k.kumar@gmail.com 
 	 Hobbies:  ['Basketball, Trolling']
Harish Poojary 
 	 DOB: December 4 
 	 Residence: San Diego 
 	 Email:  hpoojary@gmail.com 
 	 Hobbies:  ['Basketball, Hiking']

Utilizing a While Loop to print out InfoDb

  • The cell below uses a while loop to print the InfoDb
number = len(InfoDb2)
#temporary variable i set to 0
i = 0
while i < number:
    #while i is less than the number or the length of InfoDb, it prints out the data in InfoDb
    print(InfoDb2[i]["FirstName"], InfoDb2[i]["LastName"], "\n", "\t", "DOB:", InfoDb2[i]["DOB"], "\n", "\t", "Residence:", InfoDb2[i]["Residence"], "\n", "\t", "Email: ", InfoDb2[i]["Email"], "\n", "\t", "Hobbies: " ,InfoDb2[i]["Hobbies"])
    i+=1
  
Samit Poojary 
 	 DOB: February 24 
 	 Residence: San Diego 
 	 Email:  samit.poojary@gmail.com 
 	 Hobbies:  ['Soccer, Basketball, Fantasy Basketball']
Vardaan Sinha 
 	 DOB: September 28 
 	 Residence: San Diego 
 	 Email:  vardsin28@gmail.com 
 	 Hobbies:  ['Coding, Fantasy Football']
Alex Kumar 
 	 DOB: May 9 
 	 Residence: San Diego 
 	 Email:  alex.k.kumar@gmail.com 
 	 Hobbies:  ['Basketball, Trolling']
Harish Poojary 
 	 DOB: December 4 
 	 Residence: San Diego 
 	 Email:  hpoojary@gmail.com 
 	 Hobbies:  ['Basketball, Hiking']

Recursion Statement to Print out InfoDb

  • This function, known as recursion, utilizes a function that also saves us time by automating the printing procedure. It does so by incorporating multiple "if" statements.
def recursive_loop(i):
    if i < len(InfoDb2):
        record = InfoDb2[i]
        print_data(record)
        recursive_loop(i + 1)
    return
    
print("Recursive loop output\n")
recursive_loop(0)
Recursive loop output

Samit Poojary
	 Residence: San Diego
	 Birth Day: February 24
	 Email: samit.poojary@gmail.com
	 Hobbies: Soccer, Basketball, Fantasy Basketball

Vardaan Sinha
	 Residence: San Diego
	 Birth Day: September 28
	 Email: vardsin28@gmail.com
	 Hobbies: Coding, Fantasy Football

Alex Kumar
	 Residence: San Diego
	 Birth Day: May 9
	 Email: alex.k.kumar@gmail.com
	 Hobbies: Basketball, Trolling

Harish Poojary
	 Residence: San Diego
	 Birth Day: December 4
	 Email: hpoojary@gmail.com
	 Hobbies: Basketball, Hiking

Reversing the Outputting Order

  • There could be times where we would like to reverse the printing order of our list, for whatever reason.
Hockey_Names = ["Wayme Gretsky", "Joe Thorton", "Mario Lemieux", "Alex Ovechkin", "Jacques Plante", "Steve Yzerman", "Terry Sawchuk"]
#prints the list out in reverse order
print(Hockey_Names[::-1])
['Terry Sawchuk', 'Steve Yzerman', 'Jacques Plante', 'Alex Ovechkin', 'Mario Lemieux', 'Joe Thorton', 'Wayme Gretsky']

Quiz That Stores in a List of Dictionaries

import getpass, sys

questions = 5
correct = 0   

print('Hello, ' + getpass.getuser() + '!')
print("\t", "You will be asked " + str(questions) + " questions on basketball. Be mindful that this quiz is case-sensitive!")

def question_and_answer(prompt, answer):
    print("Question: " + prompt) 
    rsp = input() 
    
    if rsp == answer :
        print("\t", rsp + " is correct!")
        global correct
        correct += 1
    else:
        print ("\t", rsp + " is incorrect!")
    return rsp

Question_1 = question_and_answer("Who was the most recent three-peat in the NBA?", "Lakers")
Question_2 = question_and_answer("Who, as of right now, holds the title for most points scored?", "Kareem Abdul-Jabaar")
Question_3 = question_and_answer("Who was the most recent MVP?", "Nikola Jokic")
Question_4 = question_and_answer("Who were the most recent NBA Champions?", "Golden State Warriors")
Question_5 = question_and_answer("Who holds the record for the most points scored in a single game?", "Wilt Chamberlain")

print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions) + "!!")

Quiz = []

Quiz.append({
    "Q_1": Question_1,
    "Q_2": Question_2,
    "Q_3": Question_3,
    "Q_4": Question_4,
    "Q_5": Question_5
})

#Dictionary Component
#The code below records and displays the user's answers once the user has finished the quiz. This can possibly be used as reference for what they missed. 
def print_data(d_rec):
    print("Question 1:", d_rec["Q_1"]) 
    print("Question 2:", d_rec["Q_2"]) 
    print("Question 3:", d_rec["Q_3"])
    print("Question 4:", d_rec["Q_4"])
    print("Question 5:", d_rec["Q_5"], end="")  
    print()

print("-----------------------------------------")

print("Here is a record of your quiz:")
def for_loop():
    print("For loop output\n")
    for record in Quiz:
        print_data(record)

for_loop()
Hello, samitpoojary!
	 You will be asked 5 questions on basketball. Be mindful that this quiz is case-sensitive!
Question: Who was the most recent three-peat in the NBA?
	 Lakers is correct!
Question: Who, as of right now, holds the title for most points scored?
	 Kareem Abdul-Jabaar is correct!
Question: Who was the most recent MVP?
	 Nikola Jokic is correct!
Question: Who were the most recent NBA Champions?
	 Golden State Warriors is correct!
Question: Who holds the record for the most points scored in a single game?
	 Wilt Chamberlain is correct!
samitpoojary you scored 5/5!!
-----------------------------------------
Here is a record of your quiz:
For loop output

Question 1: Lakers
Question 2: Kareem Abdul-Jabaar
Question 3: Nikola Jokic
Question 4: Golden State Warriors
Question 5: Wilt Chamberlain