Lists and Dictionaries

  • 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
# variable of type string
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
name = "John Doe"
print("name", name, type(name))

print()


# variable of type integer
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
age = 18
print("age", age, type(age))

print()

# variable of type float
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
score = 90.0
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
print("What is variable name/key?", "value?", "type?", "primitive or collection?")
print("What is different about the list output?")
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)
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
print("What is different about the dictionary output?")
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"]))
What is the variable name/key? value? type? primitive or collection, why?
name John Doe <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
age 18 <class 'int'>

What is the variable name/key? value? type? primitive or collection, why?
score 90.0 <class 'float'>

What is variable name/key? value? type? primitive or collection?
What is different about the list output?
langs ['Python', 'JavaScript', 'Java'] <class 'list'> length 3
- langs[0] Python <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
What is different about the dictionary output?
person {'name': 'John Doe', 'age': 18, 'score': 90.0, 'langs': ['Python', 'JavaScript', 'Java']} <class 'dict'> length 4
- person["name"] John Doe <class 'str'>

List and Dictionary purpose

  • List and Dictionaries are used to collect information
  • When information is collected it is formed into patterns
    • 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
InfoDb = []

# InfoDB is a data structure with expected Keys and Values

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "FirstName": "Annika",
    "LastName": "Liao",
    "DOB": "April 26",
    "Residence": "San Diego",
    "Email": "liao.92127@gmail.com",
    "Owns_Cars": ["N/A"]
})

# Append to List a 2nd Dictionary of key/values
InfoDb.append({
    "FirstName": "Lyndsey",
    "LastName": "Couch",
    "DOB": "March 29",
    "Residence": "Hyden",
    "Email": "lyndsey@gmail.com",
    "Owns_Cars": ["Tractor"]
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'Annika', 'LastName': 'Liao', 'DOB': 'April 26', 'Residence': 'San Diego', 'Email': 'liao.92127@gmail.com', 'Owns_Cars': ['N/A']}, {'FirstName': 'Lyndsey', 'LastName': 'Couch', 'DOB': 'March 29', 'Residence': 'Hyden', 'Email': 'lyndsey@gmail.com', 'Owns_Cars': ['Tractor']}]

Formatted output of List/Dictionary - 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 -Exchange of data between programs includes the data type the method/function and the format of the data type
  • Application Programming Interface (API): write functions, receive, and return data.

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["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 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

Annika Liao
	 Residence: San Diego
	 Birth Day: April 26
	 Cars: N/A

Lyndsey Couch
	 Residence: Hyden
	 Birth Day: March 29
	 Cars: Tractor

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

Annika Liao
	 Residence: San Diego
	 Birth Day: April 26
	 Cars: N/A

Lyndsey Couch
	 Residence: Hyden
	 Birth Day: March 29
	 Cars: Tractor

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
# 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

Annika Liao
	 Residence: San Diego
	 Birth Day: April 26
	 Cars: N/A

Lyndsey Couch
	 Residence: Hyden
	 Birth Day: March 29
	 Cars: Tractor