Jiya's Custom Lists, Dictionaries, Iteration
Fav_Fruit_Dictionary = []
Fav_Fruit_Dictionary.append({
"FirstName": "Arya",
"Fav_Fruits": ["Orange", "Apple", "Mango", "Jackfruit", "Watermelon"]
})
Fav_Fruit_Dictionary.append({
"FirstName": "Jiya",
"Fav_Fruits": ["Orange", "Lemon"]
})
# add one more entry based on input from user
# ask user first name of friend and friend's fav fruits
friend_name = input("What is your friend's first name?")
friend_fruit_count = int(input("How many favorite fruits does " + friend_name + " have?"))
# make temporary list to hold fruit values from input
fruit_dictionary = []
for i in range(0, friend_fruit_count):
fruit = str(input("What is your friend's favorite fruit # " + str(i + 1) + ":"))
fruit_dictionary.append(fruit)
# now we will append the friend's name and fruit list to the main dictionary
Fav_Fruit_Dictionary.append ({
"FirstName": friend_name,
"Fav_Fruits": fruit_dictionary
})
# The list is printed
def print_data(printfruit):
print(printfruit["FirstName"] + "'s " + "favorite fruits are ", end="")
print(", ".join(printfruit["Fav_Fruits"]))
print()
def for_loop():
print("For loop output\n")
for record in Fav_Fruit_Dictionary:
print_data(record)
for_loop()
There are other methods besides append that can be used on lists. Below, I have demonstrated how to reverse the order and remove items.
print("Printing the same dictionary in reverse order:")
for record in reversed(Fav_Fruit_Dictionary):
print_data(record)
# Removing the second record in the dictionary
print("Printing the same list, with Jiya's record removed:")
del Fav_Fruit_Dictionary[1]
for record in Fav_Fruit_Dictionary:
print_data(record)
Now, I explore other type of loops, like while
def while_loop():
print("While loop output\n")
i = 0
while i < len(Fav_Fruit_Dictionary):
record = Fav_Fruit_Dictionary[i]
print_data(record)
i += 1
return
while_loop()