Python dict 字典用法與範例

本篇 ShengYu 要介紹 Python dict 字典用法與範例,dict 字典是一個 key-value 對應的容器,能用鍵(key)來查詢對應的值(value),所以一個字典裡的 key 是不會重複的具有唯一性,dict 是 python 中很好用且常用的資料結構,dict 字典它可以動態地新增與刪除資料,字典 dict 裡的資料儲存沒有順序性,以下為 Python dict 用法介紹。

以下 Python dict 用法與範例分為這幾部份,

  • Python 初始化 dict 字典
  • 建立空 dict 字典
  • 插入與更新 dict 字典裡的元素
  • 遍歷印出 dict 字典裡所有元素
  • 刪除 dict 字典裡指定的元素
  • 清空 dict 字典裡所有的元素
  • 刪除整個 dict 字典
  • 測試 key 有沒有存在 dict 字典裡

Python 初始化 dict 字典

我們以學生編號與姓名為例,學生的編號(整數)為 key,value 的部分則是填入學生的姓名(字串),
Python 中 {} 大刮號表示 dict,
我們可以在 dict 初始化時給予起始資料,初始化 dict 的寫法如下,

1
2
3
4
5
6
7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

student_dict = {1:'tom', 2:'john', 3:'alice'}
print(type(student_dict))
print(len(student_dict))
print(student_dict)

結果輸出是這樣,

1
2
3
<class 'dict'>
3
{1: 'tom', 2: 'john', 3: 'alice'}

要根據 key 來取得 value 的話,如果 dict 帶入不存在的 key 的話執行時會出現錯誤,

1
2
3
4
5
student_dict = {1:'tom', 2:'john', 3:'alice'}
print(student_dict[1])
print(student_dict[2])
print(student_dict[3])
# print(student_dict[4]) # error

輸出如下,

1
2
3
tom
john
alice

那我們換個方式以學生姓名(字串)當作 key,學生編號(整數)當作 value 來試試看,

1
2
3
4
5
student_dict = {'tom':1, 'john':2, 'alice':3}
print(student_dict['tom'])
print(student_dict['john'])
print(student_dict['alice'])
# print(student_dict['jack']) # error

輸出如下,

1
2
3
1
2
3

建立空 dict 字典

如果想建立一個空字典 dict 寫法為下,這時 student_dict 裡面是沒有任何資料的,

1
2
3
4
5
student_dict1 = {}
# 或者這樣寫
student_dict2 = dict()
print(student_dict1)
print(student_dict2)

輸出如下,

1
2
{}
{}

插入與更新 dict 字典裡的元素

這邊我們反過來,以學生姓名(字串)為 key,學生的編號(整數)當 value,

1
2
3
4
5
6
7
8
9
student_dict = {}
student_dict['Tom']=100
student_dict['John']=102
student_dict['Alice']=101

print(student_dict['Tom'])
print(student_dict['John'])
print(student_dict['Alice'])
print(student_dict)

輸出結果為

1
2
3
4
100
102
101
{'John': 102, 'Alice': 101, 'Tom': 100}

遍歷印出 dict 字典裡所有元素

印出 dict 字典裡所有元素最簡單的方式可以這樣寫

1
2
student_dict = {'Tom':100, 'John':102, 'Alice':101}
print(student_dict)

輸出結果為

1
{'Tom': 100, 'John': 102, 'Alice': 101}

或是這樣

1
2
student_dict = {'Tom':100, 'John':102, 'Alice':101}
print(student_dict.items())

輸出結果為

1
dict_items([('Tom', 100), ('John', 102), ('Alice', 101)])

或者用 for 迴圈迭代,像這樣

1
2
3
4
5
6
7
8
9
10
11
12
13
14
student_dict = {'Tom':100, 'John':102, 'Alice':101}

for key in student_dict:
print(key)

for key in student_dict.keys():
print(key)

for value in student_dict.values():
print(value)

# 迭代印出 key 與 value
for key, value in student_dict.items():
print(key + ': ' + str(value))

結果如下,

1
2
3
4
5
6
7
8
9
10
11
12
Tom
John
Alice
Tom
John
Alice
100
102
101
Tom: 100
John: 102
Alice: 101

如果不想按照 key 排序,想照 value 排序的話可以使用 python 的 sorted 函式,
這之前在 Python sort 排序 這篇介紹過了,有興趣的可以回去複習,
下面直接使用,

1
2
student_dict = {'Tom':100, 'John':102, 'Alice':101}
print(sorted(student_dict.items(), key=lambda x:x[1]))

結果如下,

1
[('Tom', 100), ('Alice', 101), ('John', 102)]

這邊要注意的是 sorted 會回傳一個新的 list,所以如果要後續處理的話,
要用一個 list 去接,像下面這樣寫,印出來的結果跟上面一樣

1
2
3
4
student_dict = {'Tom':100, 'John':102, 'Alice':101}
student_list = [] # 宣告一個空的dict,可不寫
student_list = sorted(student_dict.items(), key=lambda x:x[1])
print(student_list)

刪除 dict 字典裡指定的元素

dict 字典使用 del 來移除刪除元素,

1
2
3
4
student_dict = {'Tom':100, 'John':102, 'Alice':101}

del student_dict['Tom']
print(student_dict)

結果如下,

1
{'John': 102, 'Alice': 101}

清空 dict 字典裡所有的元素

要清空 dict 字典裡所有的元素,使用 clear(),清空後這個字典裡面就空空了,也就變成一個空字典了,

1
2
3
4
student_dict = {'Tom':100, 'John':102, 'Alice':101}

student_dict.clear()
print(student_dict)

結果如下,

1
{}

刪除整個 dict 字典

如果想毫不留情的刪除整個字典,之後再也不需要它的話,可以用 del,刪除後再去存取 dict 會執行錯誤唷!

1
2
3
4
student_dict = {'Tom':100, 'John':102, 'Alice':101}

del student_dict
# print(student_dict) # error

測試 key 有沒有存在 dict 字典裡

剛剛前述例子可以發現如果 dict 帶入不存在的 key 去存取 value 的話執行時就會出錯,但是假如今天我就是有這個需求想要試試看 dict 裡面有沒有這個 key,如果 key 有存在的話就回傳該 value,如果 key 沒有存在的話就回傳預設值,沒有給定預設值的話會回傳 None,

1
2
3
4
5
6
7
8
9
student_dict = {'Tom':100, 'John':102, 'Alice':101}
value1 = student_dict.get('Jack')
print(value1)
value2 = student_dict.get('Jack', 103)
print(value2)
value3 = student_dict.get('Alice')
print(value3)
value4 = student_dict.get('Alice', 104)
print(value4)

輸出結果如下,

1
2
3
4
None
103
101
101

下一篇將介紹 tuple 元組的用法

以上就是 Python dict 字典用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 檢查 dict 字典是否為空
Python 新手入門教學懶人包
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python tuple 元組用法與範例