温馨提示:本文最后更新于
2024-12-12 16:08:21
,某些文章具有时效性,若有错误或已失效,请在下方留言。字典
基本语法
字典是由键值对组成,基本的语法如下
{key1:value1, key2: value2, ...}
示例
# 字典示例
colors = {
"apple": "red",
"pear": "green",
"banana": "yellow"
}
基本使用
字典的基本使用,如下所示
# 获取字典中的元素 dictionary_name[key]
print(colors["apple"]) # red
# 创建空字典 {}
empty_dictionary = {}
# 修改字典中元素的值
colours["apple"] = "green"
# 遍历字典的键
for key in colors:
print(key)
# 遍历字典中的值
for key in colors:
print(colors[key])
# 同时遍历 key value
for key, value in colors.items():
print(key, value)
嵌套
字典中嵌套列表或者字典,或者列表中嵌套列表。基本的嵌套如下所示
{
key: [list],
key2: {Dict},
}
代码示例
# 字典嵌套列表
travel_log = {
"France": ["Pairs", "Lille"],
"Germany": ["Stuttgart", "Berlin"],
}
# 打印 Lille
print(travel_log["France"][1])
# 列表嵌套列表
nested_list = ["A", "B", ["C", "D"]]
print(nested_list[2][1]) # D
# 字典嵌套字典
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]) # Stuttgart
秘密竞拍
秘密竞拍游戏的流程图,如下所示
from art import logo
print(logo)
def find_highest_bidder(bidding_record):
highest_bid = 0
winner = ""
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}")
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)
© 版权声明
THE END
暂无评论内容