2017.9.3 Dictionaries

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}

 


應用

學習重點

  1. Using for loops with lists and dictionaries
  2. Writing functions with loops, lists, and dictionaries
  3. 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

 

廣告

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s