Python Day 9_Beginner – Dictionaries, nesting and the secret auction
Dictionaries
To create a dictionary the syntax is {key: Value} which is the content. For example:
{“Bug”: “An error in a program that prevents the program from running as expected.”}
If you want to add more contents to the dictionary, you would add a comma at the end and continue.
{
“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”: “ “,
}
To receive information from a dictionary list, you have to provide a key instead of a number in a list such as programming_dictionary[“Bug”] -> outputs the value
You can also add new items to dictionary -> programming_dictionary[“loop”] = “Info”
You can also create an empty dictionary from scratch:
empty_dictionary = {}
You can also wipe an existing dictionary
programming_dictionary = {} -> clears all contents
To loop through a dictionary:
for key in progamming_dictionary:
print(key)
print(programming_dictionary[key]) -> prints the key and value in order
#caution. If you do not set the parameters correctly it will only show either the key or value.
for thing in programming_dictionary:
print(thing) -> bug, function, loop
Grading Program – Coding exercise
You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values.
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
# 🚨 Don't change the code above 👆
# 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 name, score in student_scores.items():
if score > 90:
student_grades[name] = "Outstanding"
elif 81 <= score <= 90:
student_grades[name] = "Exceeds Expectations"
elif 71 <= score <= 80:
student_grades[name] = "Acceptable"
else:
student_grades[name] = "Fail"
# 🚨 Don't change the code below 👇
print(student_grades)
Nesting
Putting one dictionary into another. Similar to the following example below:
{
key: [list],
key2:{dict},
}
#Nesting a list in a dictionary
Travel_log = {
“France”: [“Paris”, “Lille”, “Dijon”]
“Germany”: [“Berlin”, “Hamburg”, “Stuttgart”],
}
#Nesting dictionary in a dictionary
travel_log = {
"France": {"cities_visited": ["Paris", "Lille", "Dijon"], "total_visits": 12},
"Germany": ["Berlin", "Hamburg", "Stuttgart"],
}
#Nesting dictionary in a list
travel_log = [
{
"country": "Thailand",
"cities_visited": ["Bangkok", "Pattaya", "Ko-tok", "Ayuttaya", "Phuket"],
"total_visits": 25
},
{
"country": "Vietnam",
"cities_visited": ["Hochimihn", "Hanoi"],
"total_visits": 1
},
]
Dictionary in a list – Coding Exercise
You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries. Your job is to create a function that can add new countries to this list.
country = input() # Add country name
visits = int(input()) # Number of visits
list_of_cities = eval(input()) # create list from formatted string
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
# Do NOT change the code above 👆
# TODO: Write the function that will allow new countries
# to be added to the travel_log.
def add_new_country(country, visits, list_of_cities):
new_country_entry = {
"country": country,
"visits": visits,
"cities": list_of_cities
}
travel_log.append(new_country_entry)
# Do not change the code below 👇
add_new_country(country, visits, list_of_cities)
print(f"I've been to {travel_log[2]['country']} {travel_log[2]['visits']} times.")
print(f"My favourite city was {travel_log[2]['cities'][0]}.")
output:
I've been to Brazil 2 times.
My favourite city was Sao Paulo.
Alternative code
def add_new_country(name, times_visited, cities_visited):
new_country = {}
new_coutnry[“country”] = name
new_country[“visits”] = times_visites
new_country[“cities”] = cities_visited
Travel_log.append(new_country)
Project 9_Secret Auction
name = input("What is your name?: ") #name of the bidder
bid = int(input("What is your bid?:$ ")) #bid amount
secret_auction = []
def bidding(name, bid):
new_bidder = {
"name": name,
"bidder": bid,
}
secret_auction.append(new_bidder)
while True:
other_bidders = input("Are there any other bidders? Type 'yes' or 'no'.")
if other_bidders == "yes":
print('\n' * 20)
name = input("What is your name?: ") # name of the bidder
bid = int(input("What is your bid?:$ ")) # bid amount
bidding(name, bid)
if other_bidders == "no":
highest_bidder = max(secret_auction, key=lambda x: x['bidder'])
highest_bid = max(bidder['bidder'] for bidder in secret_auction)
print(f"The winner is {highest_bidder['name']} with a bid of ${highest_bid}")
break
Alternative code
bids = {
bidding_finished = False
Def find_highest_bidder(bidding_record):
Highest_bid = 0
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?: $"))
bids[name] = price
should_continue = input(“Are there are other bidders? Type ‘yes or ‘no’.”)
if should_continue == “no”:
bidding_finished = True
find_highest_bidder(bids)
elif should_continue == “yes”:
clear() #for replit
'Coding : Python' 카테고리의 다른 글
Python_Day 8 (1) | 2023.12.07 |
---|---|
Python_Day 7 (0) | 2023.12.02 |
Python_Day 6 (0) | 2023.11.30 |
Python_Day 5 (1) | 2023.11.23 |
Python_Day 4 (0) | 2023.11.17 |