字典

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

食材清單

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Ingredient quantities (in grams) quantities = [500, 400, 15, 20, 30, 5]
Python 入門(開發者向)

字典

  • 字典=鍵值配對

以單字(鍵)與定義(值)標註的字典

1 https://unsplash.com/@sandym10
Python 入門(開發者向)

為何用字典?

  • username
  • email
  • preferences

 

  • ip_address
  • location

$$

  • 食譜縮放器:將食材對應到數量

使用者資訊

電腦網路

1 User image by Bilobaba Vladimir, Aviavlad; https://unsplash.com/@jjying
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = 
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta"
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta":
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta": 500
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta": 500,
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta": 500,
          "tomatoes": 400,
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta": 500,
          "tomatoes": 400, 
          "garlic": 15,
          "basil": 20, 
          "olive oil": 30,
          "salt": 5
Python 入門(開發者向)

建立字典

# Creating a dictionary
recipe = {"pasta": 500,
          "tomatoes": 400, 
          "garlic": 15,
          "basil": 20, 
          "olive oil": 30,
          "salt": 5}
Python 入門(開發者向)

依鍵存取值

  • 字典是有序的

    • 可用「以鍵取值」方式存取值
  • 需要多少 pasta?

# 找出該食材的數量
print(recipe["pasta"])
500
Python 入門(開發者向)

存取所有值

# 取得字典中所有值
print(recipe.values())
dict_values([500, 400, 15, 20, 30, 5])
Python 入門(開發者向)

存取所有鍵

# 取得字典中所有鍵
print(recipe.keys())
dict_keys(['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'])
Python 入門(開發者向)

檢視整個字典

# 列印整個字典
print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5}
# 取得所有項目(鍵值配對)
print(recipe.items())
dict_items([('pasta', 500), ('tomatoes', 400), ('garlic', 15), ('basil', 20), 
('olive oil', 30), ('salt', 5)])
Python 入門(開發者向)

新增鍵值配對

# 新增一組鍵值
recipe["parmesan"] = 50
print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
Python 入門(開發者向)

更新值

print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
# 更新既有鍵對應的值
recipe["pasta"] = 1000
print(recipe)
{'pasta': 1000, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
Python 入門(開發者向)

重複鍵

# 使用重複鍵建立字典
recipe = {"pasta": 500, "garlic": 5, 
          "garlic": 15, "basil": 20, 
          "olive oil": 30, "salt": 5}

# 列印重複鍵的值 print(recipe["garlic"])
15
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...