Lists and Dictionaries

  • ordered sequence of elements
  • lists can be modified unlike tuples which cannot be changed Purpose/Objective: can store multiple items in a single variable
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
name = "Kaylee Hou"
print("name", name, type(name))

print()


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

print()

# variable of type float
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
score = 8.16
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", "C", "R", "Bash", "C++"]
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 Kaylee Hou <class 'str'>

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

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

What is variable name/key? value? type? primitive or collection?
What is different about the list output?
langs ['Python', 'JavaScript', 'Java', 'C', 'R', 'Bash', 'C++'] <class 'list'> length 7
- 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': 'Kaylee Hou', 'age': 16, 'score': 8.16, 'langs': ['Python', 'JavaScript', 'Java', 'C', 'R', 'Bash', 'C++']} <class 'dict'> length 4
- person["name"] Kaylee Hou <class 'str'>

My InfoDb (List) with Data Abstraction and Data Definition

  • I asked one of my partners Trey for his info.
  • I added new keys "Grade," "Favorite Color," and "Favorite Books" and changed the values to data that accurately represent us. Purpose/Objective: I used a list so that I could more efficiently collect information because lists allow you to store multiple items in a single variable, I also wanted to easily update or delete these items, and lists make this easier.
InfoDb = []

InfoDb.append({
    "FirstName": "Kaylee",
    "LastName": "Hou",
    "Birthday": "October 30",
    "FavoriteColor": "Purple",
    "Grade": "12",
    "FavoriteBooks": ["A Streetcar Named Desire", "Beautiful World Where Are You", "Pride and Prejudice"]
})

# Append to List with key/values that involve my partner
InfoDb.append({
    "FirstName": "Trey",
    "LastName": "Blalock",
    "Birthday": "August 19",
    "FavoriteColor": "Pink",
    "Grade": "12",
    "FavoriteBooks": ["The Great Gatsby", "Forgive Me Leonard Peacock"]
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'Kaylee', 'LastName': 'Hou', 'Birthday': 'October 30', 'FavoriteColor': 'Purple', 'Grade': '12', 'FavoriteBooks': ['A Streetcar Named Desire', 'Beautiful World Where Are You', 'Pride and Prejudice']}, {'FirstName': 'Trey', 'LastName': 'Blalock', 'Birthday': 'August 19', 'FavoriteColor': 'Pink', 'Grade': '12', 'FavoriteBooks': ['The Great Gatsby', 'Forgive Me Leonard Peacock']}]

For Loop with Break Statement

  • Purpose: used for iterating over a sequence (list, dictionary, string), with the break statement, I can stop the loop before it goes through all the elements in my list
  • Objective: stop the loop before it loops through all the items
myList_group = ["Trey", "Ben", "Shaurya", "Kaylee", "Nicolas"]
for x in myList_group:
    if x == "Kaylee": # exit the loop when x is "Kaylee" so "Nicolas" and "Kaylee" won't be printed
        break
    print(x)
Trey
Ben
Shaurya

For loop with Index

  • I used specific syntax so that the data would be displayed in a more organized way, as before, it was all clustered together and difficult to find certain info quickly.
  • I learned that "\t" allows you to indent!
  • I added a for loop inside a for loop--> nested loop
  • I used a range function which lets me print the data as many times as I want! Range function starts with 0 and increments by 1
  • iteration: repetition of process to generate sequence of outcomes Purpose/Objective: I wanted the data to be displayed in an easily readable way, for loops allow you to repeat a specific block of code as many times as you want so you don't have to retype the code over and over again. The objective is more efficiency when coding.
def print_data(d_rec): # with the information from the dictionary
    print(d_rec["FirstName"], d_rec["LastName"])  
    print("\t", "Birthday:", d_rec["Birthday"])
    print("\t", "Favorite Color:", d_rec["FavoriteColor"])
    print("\t", "Grade:", d_rec["Grade"])
    print("\t", "FavoriteBooks: ", end="")  
    print(", ".join(d_rec["FavoriteBooks"]))  
    print()
# data abstraction hides unnecessary info from the user 

# for loop iterates on length of InfoDb
def for_loop():
    print("For loop output\n")
    for record in InfoDb:
        for index in range(2): #whatever the number in range() is, it will print the output that many times
            print_data(record)

for_loop()
For loop output

Kaylee Hou
	 Birthday: October 30
	 Favorite Color: Purple
	 Grade: 12
	 FavoriteBooks: A Streetcar Named Desire, Beautiful World Where Are You, Pride and Prejudice

Kaylee Hou
	 Birthday: October 30
	 Favorite Color: Purple
	 Grade: 12
	 FavoriteBooks: A Streetcar Named Desire, Beautiful World Where Are You, Pride and Prejudice

Trey Blalock
	 Birthday: August 19
	 Favorite Color: Pink
	 Grade: 12
	 FavoriteBooks: The Great Gatsby, Forgive Me Leonard Peacock

Trey Blalock
	 Birthday: August 19
	 Favorite Color: Pink
	 Grade: 12
	 FavoriteBooks: The Great Gatsby, Forgive Me Leonard Peacock

While Loop

  • will keep printing when the condition is true
  • Purpose/Objective: to run code a certain amount of times until the condition is met
  • purposely aborted code manually in the second example so it wouldn't run forever because I was adding by 0
  • a repeating selection statement- execute instructions based on which condition is true
  • iteration: repetition of process to generate sequence of outcomes
def while_loop():
    print("While loop output\n")
    i = 0 # initialization of index starts with 0, which means it starts counting the loop when i is 0, 0 is the first index which is my data, 1 is the second, which is Trey's data
    while i < len(InfoDb): # when my index i (0), which is the first one in the list, is less than the length of my list which is 2, 
        record = InfoDb[i] # then we set the variable record equal to the first element in my list, which is Kaylee's data
        print_data(record) # then we print the variable record, which is the first element in my list (Kaylee).
        i += 1 #this increases by 1 increment each loop, which means the index variable i will increase by 1 in each loop. 
    return # if while condition is always true, then the loop never ends. 

while_loop()
While loop output

Kaylee Hou
	 Birthday: October 30
	 Favorite Color: Purple
	 Grade: 12
	 FavoriteBooks: A Streetcar Named Desire, Beautiful World Where Are You, Pride and Prejudice

Trey Blalock
	 Birthday: August 19
	 Favorite Color: Pink
	 Grade: 12
	 FavoriteBooks: The Great Gatsby, Forgive Me Leonard Peacock

If I ran the cell block below, it would run forever!

def while_loop():
    print("While loop output\n")
    i = 0 # initialization of index (sequence index) starts with 0, which means it starts counting the loop when i is 0, 0 is the first index which is my data, 1 is the second, which is Trey's data
    while i < len(InfoDb): # when my index i (0), which is the first one in the list, is less than the length of my list which is 2, 
        record = InfoDb[i] # then we set the variable record equal to the first element in my list, which is Kaylee's data
        print_data(record) # then we print the variable record, which is the first element in my list (Kaylee).
        i += 0 #this increases by 0 increment each loop, which means the index variable i will increase by 0 in each loop. 
    return # if while condition is false it will end and return. Because 0 is always less than 2, the condition is never met so the loop never ends. 
# procedural abstraction extract shared features to generalize functionality instead of duplicating code. 
while_loop()

Recursion

Purpose: solution for specific problem, efficient to write code but may not be as efficient to run the code

  • Recursion means a defined function can call on itself
  • a complicated function can be split into sub-problems using recursion
def recursive_loop(i): # define my user function which is called recursive_loop
    if i < len(InfoDb):
        record = InfoDb[i]
        print_data(record)
        recursive_loop(i + 1) # call on myself, which is recursive_loop
    return
    
print("Recursive loop output\n")
recursive_loop(0) 
Recursive loop output

Kaylee Hou
	 Birthday: October 30
	 Favorite Color: Purple
	 Grade: 12
	 FavoriteBooks: A Streetcar Named Desire, Beautiful World Where Are You, Pride and Prejudice

Trey Blalock
	 Birthday: August 19
	 Favorite Color: Pink
	 Grade: 12
	 FavoriteBooks: The Great Gatsby, Forgive Me Leonard Peacock

Output Data in Reversed Order

  • I tried two different way to reverse my list
  • the first way uses a for loop with an iterator used as index of the element in the list
  • in the second way, I used the reverse() function which is a python built in function Purpose/Objective: return my list in a reversed order
favorite_books = ["A Streetcar Named Desire", "Beautiful World Where Are You", "Pride and Prejudice"]
for i in favorite_books[::-1]: # slicing the list so that it starts at -1 and goes backward til the first position
    print(i)
Pride and Prejudice
Beautiful World Where Are You
A Streetcar Named Desire
favorite_books = ["A Streetcar Named Desire", "Beautiful World Where Are You", "Pride and Prejudice"]
#reverse the order of the list elements
favorite_books.reverse()

#print the reversed list
print('reversed favorite books list: ', favorite_books)
reversed favorite books list:  ['Pride and Prejudice', 'Beautiful World Where Are You', 'A Streetcar Named Desire']