字典:四中基本集合之一,由鍵(key)值(value)對所組成
capital = {
"United States": "Washington DC",
"Japan": "Tokyo",
"France": "Paris",
"Russia": "Moscow"
}
1.get()取得鍵值對
print(capital.get("Japan"))
print(capital.get("France"))
Tokyo
Paris
2.update()更新鍵值對
capital.update({"Germany": "Berlin"})
print(capital)
{'United States': 'Washington DC', 'Japan': 'Tokyo', 'France': 'Paris', 'Russia': 'Moscow', 'Germany': 'Berlin'}
3.pop()刪除鍵值對
capital.pop("United States")
print(capital)
{'Japan': 'Tokyo', 'France': 'Paris', 'Russia': 'Moscow', 'Germany': 'Berlin'}
4.values()獲得所有值
print(capital.values())
dict_values(['Washington DC', 'Tokyo', 'Paris', 'Moscow', 'Berlin'])
5.items()獲得所有鍵值對
print()capital.items())
dict_items([('United States', 'Washington DC'), ('Japan', 'Tokyo'), ('France', 'Paris'), ('Russia', 'Moscow'), ('Germany', 'Berlin')])
販賣機程式:
使用字典來儲存菜單及價格,使用while迴圈讓試用者選擇菜單項目,並加入購物車中
step1.製作菜單
menu = {
"pizza": 300,
"popcorn": 150,
"chips": 60,
"french fries": 80,
"cola": 40,
"juice": 35
}
print(" 菜單:")
print("---------")
for item, price in menu.items():
print(f"{item}: {price}")
菜單:
---------
pizza: 300
popcorn: 150
chips: 60
french fries: 80
cola: 40
juice: 35
step2.讓使用者挑選品項,並加入購物車
menu = {
"pizza": 300,
"popcorn": 150,
"chips": 60,
"french fries": 80,
"cola": 40,
"juice": 35
}
print(" 菜單:")
print("---------")
cart = []
total = 0
for item, price in menu.items():
print(f"{item}: {price}")
while True:
food = input("請輸入一個菜單選項(輸入done結束)")
if food == "done":
break
elif menu.get(food) is None:
print("沒有此項商品")
else:
cart.append(food)
total += menu.get(food)
print(food, end=" ")
print(f"總共: {total}元")
菜單:
---------
pizza: 300
popcorn: 150
chips: 60
french fries: 80
cola: 40
juice: 35
請輸入一個菜單選項(輸入done結束)pizza
pizza 請輸入一個菜單選項(輸入done結束)candy
沒有此項商品
請輸入一個菜單選項(輸入done結束)chips
chips 請輸入一個菜單選項(輸入done結束)cola
cola 請輸入一個菜單選項(輸入done結束)done
總共: 400元