Lists, Dictionaries, Iteration Examples
Lists and Dictionaries Randomized Order Selection Print in Reversed Order With Function Print in Reversed Order Without using reverse() Function List and Dictionary Purpose For Loop While loop Recursion Quiz
Lists and Dictionaries
As a quick review we used variables in the introduction last week. Variables all have a type: String, Integer, Float, List and Dictionary are some key types. In Python, variables are given a type at assignment, Types are important to understand and will impact operations, as we saw when we were required to user str() function in concatenation.
- Developers often think of variables as primitives or collections. Look at this example and see if you can see hypothesize the difference between a primitive and a collection.
- Take a minute and see if you can reference other elements in the list or other keys in the dictionary. Show output.
Notes:
- The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.
- Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
print("Hi! What is your name?")
name = "Ananya Gaurav"
print("Hello! My name is", name, type(name))
print()
# variable of type integer
print("How old are you", name)
age = 15
print("I am", age, type(age))
print()
print("How many siblings do you have?")
siblings = 1
print("I have", siblings, "sibling", type(siblings))\
print(name, "what are your hobbies?")
hobbies = "playing the paino, Indian classical Dancing, coding, chess, and taking pictures!"
print("My hobbies are", hobbies, type(hobbies))
Ananya = {
"name": name,
"age": age,
"siblings": siblings,
"hobbies": hobbies
}
List and Dictionary purpose
Our society is being built on information. List and Dictionaries are used to collect information. Mostly, when information is collected it is formed into patterns. As that pattern is established you will be able collect many instances of that pattern.
- List is used to collect many instances of a pattern
- Dictionary is used to define data patterns.
- Iteration is often used to process through lists.
To start exploring more deeply into List, Dictionary and Iteration this example will explore constructing a List of people and cars.
- As we learned above, a List is a data type: class 'list'
- A 'list' data type has the method '.append(expression)' that allows you to add to the list. A class usually has extra method to support working with its objects/instances.
- In the example below, the expression is appended to the 'list' is the data type: class 'dict'
- At the end, you see a fairly complicated data structure. This is a list of dictionaries, or a collection of many similar data patterns. The output looks similar to JavaScript Object Notation (JSON), Jekyll/GitHub pages yml files, FastPages Front Matter. As discussed we will see this key/value patter often, you will be required to understand this data structure and understand the parts. Just believe it is peasy ;) and it will become so.
InfoDb = []
InfoDb.append({
"Name": "Ananya Gaurav",
"Age": "15",
"Siblings": "1",
"hobbies": ["playing the paino, Indian classical Dancing, coding, chess, and taking pictures!"],
})
def print_data(d_rec):
print("\t", "Name:", d_rec["Name"]) # \t is a tab indent
print("\t", "Age:", d_rec["Age"])
print("\t", "Siblings:", d_rec["Siblings"])
print("\t", "hobbies:", d_rec["hobbies"])
print()
def while_loop():
print("While loop\n")
i = 0
while i < len(InfoDb):
record = InfoDb[i]
print_data(record)
i += 1
return
while_loop()
peopleInfoDb = []
peopleInfoDb.append({
"Name": "Ananya",
"Nickname": "Aisha",
"Age": "15",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pasta",
"Sibling" : "Rashi,"
})
# Append to List a 2nd Dictionary of key/values
peopleInfoDb.append({
"Name": "Rashi",
"Nickname": "Gauri",
"Age": "11",
"Nationality": "Indian",
"Born?": "India",
"Eye_Color": "Brown",
"Favorite_Food" : "Pizza",
"Sibling" : "Ananya,"
})
# Print the data structure
print(peopleInfoDb)
import random
def randnum():
num = []
for i in range(7):
num.append(random.randrange(0 ,70))
print(num)
return num
def display(num):
for i in num:
print(i)
num = randnum()
display(num)
import random
print("Lets see what I will eat today?")
FOOD = ["Pasta", "Pizza", "Icecream", "Chocolate", "Soup", "Fruits","Ramen"]
FOOD = random.choice(FOOD)
TIME = ["breakfast", "lunch", "dinner"]
TIME = random.choice(TIME)
print("Today for", TIME, "I will eat....", FOOD)
routine = ["Wake up", "Brush Teeth", "Take Shower", "Get Dressed For School", "Eat Breakfast", "Pack Lunch", "Wear shoes"]
routine.reverse()
print(routine)
For Loop
Formatted output of List/Dictionary - for loop
Managing data in Lists and Dictionaries is for the convenience of passing the data across the internet, to applications, or preparing it to be stored into a database. It is a great way to exchange data between programs and programmers. Exchange of data between programs includes the data type the method/function and the format of the data type. These concepts are key to learning how to write functions, receive, and return data. This process is often referred to as an Application Programming Interface (API).
Next, we will take the stored data and output it within our notebook. There are multiple steps to this process...
- Preparing a function to format the data, the print_data() function receives a parameter called "d_rec" short for dictionary record. It then references different keys within [] square brackets.
- Preparing a function to iterate through the list, the for_loop() function uses an enhanced for loop that pull record by record out of InfoDb until the list is empty. Each time through the loop it call print_data(record), which passes the dictionary record to that function.
- Finally, you need to activate your function with the call to the defined function for_loop(). Functions are defined, not activated until they are called. By placing for_loop() at the left margin the function is activated.
def print_data(d_rec):
print(d_rec["Name"]) # using comma puts space between values
print("\t", "Nickname:", d_rec["Nickname"]) # \t is a tab indent
print("\t", "Age:", d_rec["Age"])
print("\t", "Nationality:", d_rec["Nationality"])
print("\t", "Born?:", d_rec["Born?"])
print("\t", "Eye_Color:", d_rec["Eye_Color"])
print("\t", "Favorite_Food:", d_rec["Favorite_Food"])
print("\t", "Sibling:", d_rec["Sibling"])
print()
# for loop algorithm iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in peopleInfoDb:
print_data(record)
for_loop()
Alternate methods for iteration - while loop
In coding, there are usually many ways to achieve the same result. Defined are functions illustrating using index to reference records in a list, these methods are called a "while" loop and "recursion".
- 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()
def while_loop():
print("While loop output\n")
i = 0
while i < len(peopleInfoDb):
record = peopleInfoDb[i]
print_data(record)
i += 1
return
while_loop()
Calling a function repeatedly - recursion
This final technique achieves looping by calling itself repeatedly.
- recursive_loop(i) function is primed with the value 0 on its activation with "recursive_loop(0)"
- the last statement indented inside the if statement "recursive_loop(i + 1)" activates another call to the recursive_loop(i) function, each time i is increasing
- ultimately the "if i < len(InfoDb):" will evaluate to false and the program ends
def recursive_loop(i):
if i < len(peopleInfoDb):
record = peopleInfoDb[i]
print_data(record)
recursive_loop(i + 1)
return
print("Recursive loop output\n")
recursive_loop(0)
import getpass, sys
question1 = "Who is Rashi's Sibling?"
question2 = "What is Ananya's favorite food?"
question3 = "What color are Rashi's eyes?"
question4 = "What is Ananya's Nationality?"
question5 = "How old is Ananya?"
Test = { question1: "Ananya",
question2 : "Pasta",
question3: "Brown",
question4: "Indian",
question5 : "15",
}
def question_and_answer(prompt):
print("Question: " + prompt)
msg = input()
print("Answer: " + msg)
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
def evaluate_answer(question, response, correct):
if response == Test.get(question):
print(response + " is correct!")
correct += 1
else:
print(response + " is incorrect!")
return correct
questions = 5
correct = 0
print('Hi!!!, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_and_answer("Are you ready to take the amazing and fun test?")
rsp = question_with_response(question1)
correct = evaluate_answer(question1, rsp, correct)
print(correct)
rsp = question_with_response(question2)
correct = evaluate_answer(question2, rsp, correct)
print(correct)
rsp = question_with_response(question3)
correct = evaluate_answer(question3, rsp, correct)
print(correct)
rsp = question_with_response(question4)
correct = evaluate_answer(question4, rsp, correct)
print(correct)
rsp = question_with_response(question5)
correct = evaluate_answer(question5, rsp, correct)
print(correct)
print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))