iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
Software Development

來一場軟體開發學習之旅系列 第 6

Day 6:字典 ─ 讓資料有名字

  • 分享至 

  • xImage
  •  

想像一下,你想存放一個學生的資訊:
姓名:Allen
年齡:25
身高:175
用清單(List)的話:
student = ["Allen", 25, 175]
print(student[0]) # Allen

問題:student[0] 是姓名?年齡?身高?
這時候就需要 字典(Dictionary),用鍵(Key)對應值(Value)。

  1. 字典的基本用法
    student = {
    "name": "Allen",
    "age": 25,
    "height": 175
    }
    #讀取資料
    print(student["name"]) # Allen
    print(student["age"]) # 25
    #修改資料
    student["age"] = 26
    print(student)
    #新增資料
    student["is_student"] = True
    print(student)
    #刪除資料
    del student["height"]
    print(student)

字典的結構: { "key": value }
key通常是字串(例如 "name")
value可以是數字、字串、布林值,甚至是清單或字典

你可以用迴圈快速處理字典的所有內容:
2. 字典與迴圈
student = {
"name": "Allen",
"age": 26,
"is_student": True
}

for key, value in student.items():
print(key, ":", value)

輸出:
name : Allen
age : 26
is_student : True

字典裡面還可以放字典,適合描述更複雜的資料。
4. 巢狀結構(Nested Dictionary)
students = {
"A001": {"name": "Allen", "age": 25},
"A002": {"name": "Lily", "age": 22},
"A003": {"name": "Tom", "age": 24}
}

print(students["A002"]["name"]) # Lily

常見於資料庫或 API 回傳的資料格式。

學會了字典(Dictionary),它比清單更能直覺表達有意義的資料。
明天,將學習集合(Set),了解如何處理不重複的資料,並且探討集合在資料運算上的強大應用。


上一篇
Day 5:資料結構 ─ 陣列與清單
系列文
來一場軟體開發學習之旅6
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言