Learning about Lists and Dictionaries with InfoDb
My journey with Data Abstraction using Python Lists and Python Dictionaries.
- Python and Displaying Variables
- Lists and Dictionaries
- Formatting my Lists/Dictionaries - for loop command
- Another method of Formatting - while loop
- The third Formatting technique - recursion
# variable of type string
name = "Jeffrey Lee"
print("name", name, type(name))
# variable of type integer
age = 17
print("age", age, type(age))
# variable of type float
score = 20.0
print("score", score, type(score))
print()
# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "Bash"]
print("langs", langs, type(langs))
print("- langs[3]", langs[3], type(langs[3]))
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))
print('- person["name"]', person["name"], type(person["name"]))
InfoDb = []
# Append to List a Dictionary of key/values related to a person and preferences
InfoDb.append({
"FirstName": "Jeffrey",
"LastName": "Lee",
"DOB": "December 27",
"Residence": "San Diego",
"Email": "leejeffreysc@gmail.com",
"Favorite_Food": ["Thai Food"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Avinh",
"LastName": "Huynh",
"DOB": "December 27",
"Residence": "San Diego",
"Email": "avinhahuynh@gmail.com",
"Favorite_Food": ["Vietnamese Food"]
})
# Print the data structure
print(InfoDb)
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", "Favorite Food: ", end="") # end="" make sure no return occurs
print(", ".join(d_rec["Favorite_Food"])) # join allows printing a string list with separator
print()
# for loop iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
Another method of Formatting - while loop
- 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()
- Using Python, I used the "while loop" command to format my dictionary in a numerical order for the output to display.
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)