Lists, Dictionaries, Iteration
An introduction to Data Abstraction using Python Lists [] and Python Dictionaries {}.
# variable of type string
name = "Aaron Rubin"
print("name", name, type(name))
# variable of type integer
age = 14
print("age", age, type(age))
# variable of type float
weight = 141
print("weight", weight, type(weight))
print()
# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java"]
print("langs", langs, type(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,
"weight": weight,
"langs": langs
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
InfoDb = []
# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "Aaron",
"LastName": "Rubin",
"DOB": "November 5",
"Residence": "San Diego",
"Email": "aaronr06138@gmail.com",
"weight": ["141"]
}) #InfoDb [0]
InfoDb.append({
"FirstName": "Chris",
"LastName": "Rubin",
"DOB": "March 18",
"Residence": "San Diego",
"Email": "jabba67891@gmail.com",
"weight": ["148"]
}) #InfoDb [1]
print()
print()
print(InfoDb)
# Append to List a Dictionary of key/values related to a person and cars
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", "weight:141", end="") # end="" make sure no return occurs
# for loop iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
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()
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)
for index in range (len(InfoDb)):
print_data(InfoDb[index])