Dictionaries Nesting
dictionaries are very useful because they allow us to group together and tag related pieces of information.
Every dictionary has two parts to it.
On the left hand side is the key, and that is the equivalent of the word in the dictionary,
and then it's also got an associated value.
That would be the equivalent of the actual definition of the word.
{Key: Value}
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
#Retriving items from dictionary.
print(programming_dictionary["Bug"])
#output
An error in a program that prevents the program from running as expected.
#Adding new items to distionary.
programming_dictionary["Loop"] = "The action of doing something over and over again."
print(programming_dictionary)
#output
{'Bug': 'An error in a program that prevents the program from running as expected.', 'Function': 'A piece of code that you can easily call over and over again.', 'Loop': 'The action of doing something over and over again.'}
#Create an empty dictionary.
empty_dictionary = {}
#Wipe an existing empty_dictionary
programming_dictionary = {}
print(programming_dictionary)
#output
{}
#Edit an item in a empty_dictionary
programming_dictionary["Bug"] = "A moth in your computer."
print(programming_dictionary)
#output
{"Bug": "A moth in your computer.", "Function": "A piece of code that you can easily call over and over again.", "Loop": "The action of doing something over and over again."}
#Loop through a empty_dictionary
for key in programming_dictionary:
print(key)
print(programming_dictionary[key])
#output
Bug
A moth in your computer.
Function
A piece of code that you can easily call over and over again.
Loop
The action of doing something over and over again.
Grading Program
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
#TODO-1: Create an empty dictionary called student_grades.
student_grades = {}
#TODO-2: Write your code below to add the grades to student_grades.👇
for student in student_scores:
score = student_scores[student]
if score > 90:
#if 구문까지는 만들었는데 출력값 입력을 잘못함 ㅠ
student_grades[student] = "Outstanding"
elif score > 80:
student_grades[student] = "Exceeds Expectations"
elif score > 70:
student_grades[student] = "Acceptable"
else:
student_grades[student] = "Fail"
print(student_grades)
#output
{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}
Nesting
nesting lists and dictionaries is just a matter of putting one inside the other.
{
Key: [List],
Key2: {Dict},
}
#Nesting
capitals = {
"France": "Paris",
"Germany": "Berlin",
}
#Nesting a List in a Dictionary
travel_log = {
"France": ["Paris", "Lille", "Dijon"],
#"France": "Paris", "Lille", "Dijon" doesn't really work because each key can only have one value.
"Germany": ["Berlin", "Hamburg", "Stuttgart"],
}
#Nesting Dictionary in a Dictionary
travel_log = {
"France": {"cities_visited": ["Paris", "Lille", "Dijon"], "total_visits": 12},
"Germany": {"cities_visited": ["Berlin", "Hamburg", "Stuttgart"], "total_visits": 5},
}
#Nesting Dictionaries in Lists
travel_log = [
{
"country": "France",
"cities_visited": ["Paris", "Lille", "Dijon"],
"total_visits": 12,
},
{
"country": "Germany",
"cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
"total_visits": 5,
},
]
The data types inside a dictionary can be completely mixed up if we want it to.
But what can't change is we still need a key and a value separated by a colon.
Dictionary in List
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇
def add_new_country(country_visited, times_visited, cities_visited):
new_country = {}
new_country["country"] = country_visited
new_country["visits"] = times_visited
new_country["cities"] = cities_visited
travel_log.append(new_country)
#dictionary 만든 후에 list에 추가
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
Blind Auction
from replit import clear
from art import logo
print(logo)
bids = {}
bidding_finished = False
def find_highest_bidder(bidding_record):
highest_bid = 0
winner = ""
# bidding_record = {"Angela": 123, "James": 321}
for bidder in bidding_record:
bid_amount = bidding_record[bidder]
if bid_amount > highest_bid:
highest_bid = bid_amount
winner = bidder
print(f"The winner is {winner} with a bid of ${highest_bid}")
while not bidding_finished:
name = input("What is your name?: ")
price = int(input("What is your bid?: $"))
#because price should be integer to compare with highest_bid
bids[name] = price
should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
if should_continue == "no":
bidding_finished = True
find_highest_bidder(bids)
elif should_continue == "yes":
clear()
visualise code execution
https://pythontutor.com/