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.

Notes:

  • Key Types of Variables: tring, Integer, Float, List and Dictionary.
  • Difference between a primative and a collection: A primative type is a basic building block of programming. A collection requires objects for manipulation.
# variable of type string
name = "Sreeja Gangapuram"
print("name", name, type(name))

print()


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

print()

# variable of type float
score = 100.0
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java"]
print("langs", langs, type(langs), "length", len(langs))
print("- langs[0]", langs[0], type(langs[0]))

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), "length", len(person))
print('- person["name"]', person["name"], type(person["name"]))
name Sreeja Gangapuram <class 'str'>

age 15 <class 'int'>

score 100.0 <class 'float'>

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

person {'name': 'Sreeja Gangapuram', 'age': 15, 'score': 100.0, 'langs': ['Python', 'JavaScript', 'Java']} <class 'dict'> length 4
- person["name"] Sreeja Gangapuram <class 'str'>

Randomized Order Selection

import random
print("Book choices")
books = ["A Good Girl's Guide to Murder", "The Silent Patient", "Verity", "The Spanish Love Deception"]
randomBook = random.choice(books)
print("A Good Book reccomendation is", randomBook+ ":)")
Book choices
A Good Book reccomendation is The Spanish Love Deception:)
cakes = ["Chocolate", "Red Velvet", "Vanilla", "Chocolate Chip", "Confetti"]
cakes.reverse()
print('\nReversed List:', cakes)
Reversed List: ['Confetti', 'Chocolate Chip', 'Vanilla', 'Red Velvet', 'Chocolate']
cakes = ["Chocolate", "Red Velvet", "Vanilla", "Chocolate Chip", "Confetti"]
#initializing i with the length minus 1
i = len(cakes)-1

print('\nReversed List:', cakes)
#checking that i is greater than or equal to 0. 
while i >= 0:
      print(cakes[i])
      #decrementing by one each time
      i = i-1
Reversed List: ['Chocolate', 'Red Velvet', 'Vanilla', 'Chocolate Chip', 'Confetti']
Confetti
Chocolate Chip
Vanilla
Red Velvet
Chocolate

List and Dictionary Purpose

Our society is being built 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 be able collect many instances of that pattern.

  • List is used to collect many instances of a pattern
  • 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 this example will explore constructing a List of people and cars.

  • As we learned above, a List is a data type: class 'list'
  • A 'list' data type has the method '.append(expression)' that allows you to add to the list. A class usually has extra method to support working with its objects/instances.
  • In the example below, the expression is 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, or a collection of many similar data patterns. The output looks similar to JavaScript Object Notation (JSON), Jekyll/GitHub pages yml files, FastPages Front Matter. As discussed we will see this key/value patter often, you will be required to understand this data structure and understand the parts. Just believe it is peasy ;) and it will become so.
InfoDb = []

# InfoDB is a data structure with expected Keys and Values

# Append to List a Dictionary of book titles, their authors, published date, and more information about them. 
InfoDb.append({
    "BookTitle": "A Good Girl's Guide to Murder",
    "Author": "Holly Jackson",
    "DatePublished": "May 2, 2019",
    "Genre(s)": "Mystery, Young adult fiction",
    "Review": ["4.4"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "BookTitle": "The Silent Patient",
    "Author": "Alex Michaelides",
    "DatePublished": "February 5, 2019",
    "Genre(s)": "Thriller, Novel, Mystery, Suspense, Psychological Fiction, Crime Fiction",
    "Review": ["4.2"]
})

# Print the data structure
print(InfoDb)
[{'BookTitle': "A Good Girl's Guide to Murder", 'Author': 'Holly Jackson', 'DatePublished': 'May 2, 2019', 'Genre(s)': 'Mystery, Young adult fiction', 'Review': ['4.4']}, {'BookTitle': 'The Silent Patient', 'Author': 'Alex Michaelides', 'DatePublished': 'February 5, 2019', 'Genre(s)': 'Thriller, Novel, Mystery, Suspense, Psychological Fiction, Crime Fiction', 'Review': ['4.2']}]

For Loop

Managing data in Lists and Dictionaries is for the convenience of passing the data across the internet, to applications, or preparing it to be stored into a database. It is a great way to exchange data between programs and programmers. Exchange of data between programs includes the data type the method/function and the format of the data type. These concepts are key to learning how to write functions, receive, and return data. This process is often referred to as an Application Programming Interface (API).

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.
# print function: given a dictionary of InfoDb content
def print_data(d_rec):
    print(d_rec["BookTitle"])  # using comma puts space between values
    print("\t", "Author:", d_rec["Author"]) # \t is a tab indent
    print("\t", "DatePublished:", d_rec["DatePublished"])
    print("\t", "Genre(s):", d_rec["Genre(s)"])
    print("\t", "Review:", d_rec["Review"])
    print()


# for loop algorithm 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

A Good Girl's Guide to Murder
	 Author: Holly Jackson
	 DatePublished: May 2, 2019
	 Genre(s): Mystery, Young adult fiction
	 Review: ['4.4']

The Silent Patient
	 Author: Alex Michaelides
	 DatePublished: February 5, 2019
	 Genre(s): Thriller, Novel, Mystery, Suspense, Psychological Fiction, Crime Fiction
	 Review: ['4.2']

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()
# while loop algorithm contains an initial n and an index incrementing statement (n += 1)
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

A Good Girl's Guide to Murder
	 Author: Holly Jackson
	 DatePublished: May 2, 2019
	 Genre(s): Mystery, Young adult fiction
	 Review: ['4.4']

The Silent Patient
	 Author: Alex Michaelides
	 DatePublished: February 5, 2019
	 Genre(s): Thriller, Novel, Mystery, Suspense, Psychological Fiction, Crime Fiction
	 Review: ['4.2']

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
# recursion algorithm loops incrementing on each call (n + 1) until exit condition is met
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

A Good Girl's Guide to Murder
	 Author: Holly Jackson
	 DatePublished: May 2, 2019
	 Genre(s): Mystery, Young adult fiction
	 Review: ['4.4']

The Silent Patient
	 Author: Alex Michaelides
	 DatePublished: February 5, 2019
	 Genre(s): Thriller, Novel, Mystery, Suspense, Psychological Fiction, Crime Fiction
	 Review: ['4.2']

Quiz

This quiz stores in the list of dictionaries.

import getpass, sys
#used three variables (q1, q2, q3) for the questions. 
q1 = "Who is the author of A Good Girl's Guide To Murder?"
q2 = "What is the rating of The Silent Patient?"
q3 = "In what year were A Good Girl's Guide to Murder and The Silent Patient published?"

#defining a dictionary using the above questions and answers. 
quiz = { q1: "Holly Jackson", 
         q2: "4.2",
         q3: "2019"
        }
    

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

#evaluating the answer using the get() function on the dictionary. "Python dictionary method get() returns a value for the given key. If key is not available then returns default value None."
def evaluate_answer(question, response, correct):
    if response == quiz.get(question):
      print(response + " is correct!")
      correct += 1
    else:
      print(response + " is incorrect!")
    return correct
    


questions = 3
correct = 0

print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_and_answer("Are you ready to take a test?")

rsp = question_with_response(q1)
correct = evaluate_answer(q1, rsp, correct)
print(correct)

rsp = question_with_response(q2)
correct = evaluate_answer(q2, rsp, correct)
print(correct)


rsp = question_with_response(q3)
correct = evaluate_answer(q3, rsp, correct)
print(correct)

print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
Hello, SreejaGangapuram running /usr/local/bin/python3
You will be asked 3 questions.
Question: Are you ready to take a test?
Answer: yes
Question: Who is the author of A Good Girl's Guide To Murder?
Holly Jackson is correct!
1
Question: What is the rating of The Silent Patient?
4.2 is correct!
2
Question: In what year were A Good Girl's Guide to Murder and The Silent Patient published?
2019 is correct!
3
SreejaGangapuram you scored 3/3