Dictionaries
1.
# 在 dictionary 中創造新的 key dict_name[new_key] = new_value
2.
# 改變其中一個 key 的 value dict_name[key] = new_value
3.
# 刪除一個 key del dict_name[key_name]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
del stock['banana']
print(stock)
{‘apple’: 0, ‘orange’: 32, ‘pear’: 15}
stock['apple']=2 print(stock)
{‘apple’: 2, ‘orange’: 32, ‘pear’: 15}
stock['banaba']=6 print(stock)
{‘apple’: 2, ‘orange’: 32, ‘pear’: 15, ‘banaba’: 6}
應用
學習重點
- Using for loops with lists and dictionaries
- Writing functions with loops, lists, and dictionaries
- Updating data in response to changes in the environment (for instance, decreasing the number of bananas in stock by 1 when you sell one).
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total = total + prices[item]
stock[item] = stock[item] - 1
return total