Week 2 - Python Lists and Dictionaries
- List of All Hacks
- Hack #1: Add records to the InfoDb
- Hack #2: For loop with an index
- Hack #3: Output data in reverse order
- Hack #4: Other Methods with Lists
- Hack #5: Get Dictionary Values with Input
- Hack #6: Quiz Using Dictionaries
- Using While Loop
- Recursion
- Food Dictionary
- To Do List Using Dictionary and Input
List of All Hacks
- Add a couple of records to the InfoDb
- Try to do a for loop with an index
- Would it be possible to output data in a reverse order?
- Are there other methods that can be performed on lists?
- Could you create new or add to dictionary data set? Could you do it with input?
- Make a quiz that stores in a List of Dictionaries.
InfoDb = []
# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "John",
"LastName": "Mortensen",
"DOB": "October 21",
"Residence": "San Diego",
"Email": "jmortensen@powayusd.com",
"Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Sunny",
"LastName": "Naidu",
"DOB": "August 2",
"Residence": "Temecula",
"Email": "snaidu@powayusd.com",
"Owns_Cars": ["4Runner"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Sophia",
"LastName": "Tang",
"DOB": "Septembr 4",
"Residence": "San Diego",
"Email": "sophiat14470@powayusd.com",
"Owns_Cars": ["None"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Random",
"LastName": "Person",
"DOB": "January 1",
"Residence": "New York City",
"Email": "randomemail@domain.com",
"Owns_Cars": ["Tesla"]
})
# Print the data structure
print(InfoDb)
Define the printing data function (prints the data from the input)
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 record in range(0, len(InfoDb)):
print_data(InfoDb[record])
for record in reversed(range(0, len(InfoDb))):
print_data(InfoDb[record])
numList = [4, 7, 2, 67, 45, 90, 21, 34, 65, 31]
# Find the max of the list
greatest = 0
for i in range(0, 10):
if (numList[i] > greatest):
greatest = numList[i]
print("The greatest in this list is " + str(greatest))
least = 199999
for i in range(0, 10):
if (numList[i] < least):
least = numList[i]
print("The least in this list is " + str(least))
newDb = []
num = input("How many records do you want to enter in?")
def getInput():
inputQuestions = ["Enter in a first name: ", "Enter in a last name: ", "Enter in a DOB: ", "Enter in a residence: ", "Enter in an email: ", "How many cars does this person have?", "Enter in owned car: "]
inputList = []
for i in range(0, 5):
temp = input(inputQuestions[i])
inputList.append(temp)
cars = int(input(inputQuestions[5]))
for i in range (0, cars):
temp = input(inputQuestions[6])
inputList.append(temp)
return(inputList)
for i in range(0, int(num)):
carsList = []
add = getInput()
for j in range (5, len(add)):
carsList.append(add[j])
newDb.append({
"FirstName": add[0],
"LastName": add[1],
"DOB": add[2],
"Residence": add[3],
"Email": add[4],
"Owns_Cars": carsList
})
print(newDb)
import getpass, sys
def question(prompt, answer):
msg = input("Question: " + prompt)
if msg == answer:
print(msg + " is correct!")
return(1)
else:
print(msg + " is incorrect!")
return(0)
print("Welcome to a quiz about me :)")
# Append to List a Dictionary of key/values related to a person and cars
quiz = {
"1. What is my name?": "Sophia",
"2. What is my favorite food (one word)?": "noodles",
"3. What month am I born in?": "September",
"4. What school do I go to (four letters, all caps)?": "DNHS",
}
numqs = 4
correct = 0
for item in quiz:
num = question(item, quiz[item])
correct = correct + num
print("You scored" + str(correct) +"/" + str(numqs))
print("Your percentage is " + str(correct/numqs*100) + "%! Good work!")
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)
food = []
# create print_data function for food
def print_food(d_rec):
print(d_rec["FoodName"])
print("\t", "Cuisine:", d_rec["Cuisine"])
print("\t", "Taste:", d_rec["Taste"])
print("\t", "Ingredients: ", end="")
print(", ".join(d_rec["Ingredients"]))
print("\t", "Preparation Time:", d_rec["Preparation Time"])
print("\t", "Cook Time:", d_rec["Cooking Time"])
print("\t", "Rating:", d_rec["Rating"])
print()
# append information about different foods in the form of dictionaries
food.append({
"FoodName": "Soup Noodles",
"Cuisine": "Chinese",
"Taste": "Light and savory",
"Ingredients": ["Noodles", "water", "bok choy", "meats", "vegetables", "poached egg", "tomato"],
"Preparation Time": "20 minutes",
"Cooking Time": "15 minutes",
"Rating": "9/10",
})
food.append({
"FoodName": "Sushi",
"Cuisine": "Japanese",
"Taste": "Light and savory",
"Ingredients": ["Rice", "seaweed", "salmon", "avocado", "ingredients as you wish"],
"Preparation Time": "30 minutes",
"Cooking Time": "15 minutes",
"Rating": "9/10",
})
food.append({
"FoodName": "Pizza",
"Cuisine": "Italian",
"Taste": "Savory/cheesy",
"Ingredients": ["Tomato sauce", "dough", "pepperoni", "pineapple", "other toppings"],
"Preparation Time": "30 minutes",
"Cooking Time": "1 hour",
"Rating": "7/10",
})
food.append({
"FoodName": "Fried rice",
"Cuisine": "Chinese",
"Taste": "Savory",
"Ingredients": ["Leftover rice", "eggs", "peas", "carrots", "other veggies/meats"],
"Preparation Time": "10 minutes",
"Cooking Time": "10 minutes",
"Rating": "8/10",
})
for record in range(0, len(food)):
print_food(food[record])
ToDoList = []
print("Welcome to a todo list to keep track of what you need to do!")
num = input("How many todo items do you need to enter in?")
def getInput():
inputQuestions = ["Task name: ", "Category (Ex: home, school): ", "Estimated Time: ", "Due Date: ", "Urgency Value (1 for least, 10 for most): "]
inputList = []
for i in range(0, 5):
temp = input(inputQuestions[i])
inputList.append(temp)
return(inputList)
for i in range(0, int(num)):
add = getInput()
ToDoList.append({
"Task Name": add[0],
"Category": add[1],
"Estimated Time": add[2],
"Due Date": add[3],
"Urgency": add[4],
})
# create print_data function for todo list
def print_tasks(d_rec):
print(d_rec["Task Name"])
print("\t", "Category:", d_rec["Category"])
print("\t", "Estimated Time:", d_rec["Estimated Time"])
print("\t", "Due Date:", d_rec["Due Date"])
print("\t", "Urgency:", d_rec["Urgency"])
print()
for record in range(0, len(ToDoList)):
print_tasks(ToDoList[record])