Lists, Dictionaries, Iteration
An introduction to Data Abstraction using Python Lists [] and Python Dictionaries {}.
- List and Dictionary purpose
- Formatted output of List/Dictionary - for loop
- Alternate methods for iteration - while loop
- Calling a function repeatedly - recursion
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 = []
#Append to player profile of Deebo Samuel in the 2021 NFL Season
InfoDb.append({
"FirstName": "Deebo",
"LastName": "Samuel",
"Position": "Wide Reciever",
"NFL Draft Pick": "Second Round Pick 36",
"NFL Top 100 Rank": "19",
"Total Yards": "1770",
"Total TDs": "14",
"Teams": ["San Francisco 49ers"]
})
#Append to player profile of Matthew Stafford in the 2021 NFL Season
InfoDb.append({
"FirstName": "Matthew",
"LastName": "Stafford",
"Position": "Quarterback",
"NFL Draft Pick": "First Round Pick 1",
"NFL Top 100 Rank": "27",
"Total Yards": "4886",
"Total TDs": "41",
"Teams": ["Detroit Lions", "Los Angeles Rams"]
})
# Prints 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.
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"])
print("\t", "Position:", d_rec["Position"])
print("\t", "NFL Draft Pick:", d_rec["NFL Draft Pick"])
print("\t", "NFL Top 100 Rank:", d_rec["NFL Top 100 Rank"])
print("\t", "Total Yards:", d_rec["Total Yards"])
print("\t", "Total TDs:", d_rec["Total TDs"])
print("\t", "Teams: ", end="")
print(", ".join(d_rec["Teams"]))
print()
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()
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()
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)