Day 9 - Udemy - 100 Days of Python 学习笔记
·
Udemy - 100 Days of Code: The Complete Python Pro Bootcamp
Day 9 - Beginner - Dictionaries & Nesting
68. Dictionaries
# Create Dictionaries
this_dict = {
"brand": "Ford",
"electric": False,
"year": 1964,
}
this_dict2 = dict(brand = "Ford", electric = False, year = 1964)
# Access Items
print(this_dict["brand"])
print(this_dict.get("brand"))
print(this_dict.keys())
print(this_dict.values())
print(this_dict.items())
# Change Items
this_dict["year"] = 2018
this_dict.update({"year": 2018})
# Add Items
this_dict["model"] = "Mustang"
this_dict.update({"model": "Mustang"})
# Remove Items
this_dict.pop("brand")
this_dict.popitem()
del this_dict["brand"]
del this_dict
this_dict.clear()
# Loop Dictionaries
for key in this_dict:
print(key)
print(this_dict[key])
for key in this_dict.keys():
print(key)
for value in this_dict.values():
print(value)
for key, value in this_dict.items():
print(key, value)
69. Nested Lists and Dictionaries
# Nested List in List
nested_list = ["A", "B", ["C", "D"]]
print(nested_list[2][1])
# Nested List in Dictionary
travel_log = {
"France": ["Paris", "Lille", "Dijon"],
"Germany": ["Stuttgart", "Berlin"],
}
print(travel_log["France"][1])
# Nested Dictionary in Dictionary
travel_log = {
"France": {
"cities_visited": ["Paris", "Lille", "Dijon"],
"total_visits": 12
},
"Germany": {
"cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
"total_visits": 5
},
}
print(travel_log["Germany"]["cities_visited"][2])
70. Blind Auction Project
def find_highest_bidder(bidding_record):
winner = ""
highest_bid = 0
for bidder in bidding_record:
if highest_bid < bidding_record[bidder]:
winner = bidder
highest_bid = bidding_record[bidder]
print(f"The winner is {winner} with a bid of ${highest_bid}")
def find_highest_bidder2(bidding_record):
winner = max(bidding_record, key = bidding_record.get)
highest_bid = bidding_record[winner]
print(f"The winner is {winner} with a bid of ${highest_bid}")
bids = {}
continue_bidding = True
while continue_bidding:
name = input("What is your name?: ")
price = int(input("What is your bid?: $"))
bids[name] = price
should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
if should_continue == "no":
continue_bidding = False
find_highest_bidder(bids)
elif should_continue == "yes":
print("\n" * 20) # Clear the output更多推荐


所有评论(0)