1. 程式人生 > 實用技巧 >Python3筆記019 - 4.4 字典

Python3筆記019 - 4.4 字典

第4章 序列的應用

python的資料型別分為:空型別、布林型別、數字型別、位元組型別、字串型別、元組型別、列表型別、字典型別、集合型別

在python中序列是一塊用於存放多個值的連續記憶體空間。

python內建了5種序列分別是元組、列表、字典、集合、字串

本章將介紹元組、列表、字典、集合四種序列型別,字串將在第5章介紹

4.4 字典

字典的特徵:

1、通過鍵而不是通過索引來讀取

2、字典是可變的,並且可以任務巢狀

3、字典中的鍵必須唯一

4、字典中的鍵必須不可變

5、從3.6版本開始,是有序序列

4.4.1 字典的建立和刪除

1、直接使用{}建立字典

dictonary = {"key1":"value1", "key2":"value2", ..., "keyn":"valuen"}
引數說明
dictionary表示字典名稱
key1、key2、...keyn表示元素的鍵,必須唯一
value1、value2、...、valuen表示元素的值,不須唯一
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(type(dict1))
output:
<class 'dict'>
dictionary = {} # 空字典
dictionary = dict() # 空字典

2、通過對映函式建立字典

dictionary = dict(zip(list1, list2))
引數說明
dictionary表示字典名稱
zip()函式用於將多個列表或元組對應位置的元素組合為元組,並返回包含這些內容的zip物件
list1 = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
list2 = ["Monday","Tuesday","wednesday","Thursday","Friday","Saturday","Sunday"]
dictionary = dict(zip(list1, list2))
print(type(dictionary))
print(dictionary)
output:
<class 'dict'>
{'星期一': 'Monday', '星期二': 'Tuesday', '星期三': 'wednesday', '星期四': 'Thursday', '星期五': 'Friday', '星期六': 'Saturday', '星期日': 'Sunday'}

3、通過給定的關鍵字引數建立字典

dictionary = dict(key1=value1, key2=value2, ..., keyn=valuen)
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
print(type(dictionary))
print(dictionary)
output:
<class 'dict'>
{'key1': 'value1', 'key2': 'value2', 'keyn': 'valuen'}

4、刪除字典

del dictionary
dictionary.clear()
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
del dictionary
print(dictionary)
output:
NameError: name 'dictionary' is not defined
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
dictionary.clear()
print(dictionary)
output:
{}

4.4.2 通過鍵值對訪問字典

1、通過鍵訪問值

ditionary[key]
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(dict1["Monday"])
output:
星期一

2、通過字典物件的get()方法

dictionary.get(key[,default])
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(dict1.get("Monday"))
output:
星期一

4.4.3 遍歷字典

1、keys()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.keys():
print(i)
output:
Monday
Tuesday
wednesday
Thursday
Friday
Saturday
Sunday

2、values()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.values():
print(i)
output:
星期一
星期二
星期三
星期四
星期五
星期六
星期日

3、items()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.items():
print(i)
output:
('Monday', '星期一')
('Tuesday', '星期二')
('wednesday', '星期三')
('Thursday', '星期四')
('Friday', '星期五')
('Saturday', '星期六')
('Sunday', '星期日')

4.4.4 新增、修改、刪除字典元素

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六",}
# 新增
dict1["Sunday"]="星期日"
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日'}
# 修改
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
dict1["Sunday"]="星期天"
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期天'}
# 刪除
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
del dict1["Sunday"]
# 如果要刪除的元素不存在,會丟擲異常,可以先做個判斷
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
if "Sunday" in dict1:
del dict1["Sunday"]
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六'}

4.4.5 字典推導式

import random
randomdict = {i:random.randint(10,100) for i in range(1,5)}
print("生成的字典為:",randomdict)
output:
生成的字典為: {1: 41, 2: 40, 3: 45, 4: 10}
# 拓展:值最大的字典
def max_pairs(dic):
if len(dic) == 0:
return dic
max_val = max(map(lambda v: v[1], dic.items()))
return [item for item in dic.items() if item[1] == max_val] r = max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
print(r) # [('b', 5), ('d', 5)]
# 拓展:合併兩個字典
def merge_dict2(dic1, dic2):
return {**dic1, **dic2} # python3.5後支援一行程式碼實現合併字典 merge_dict({'a': 1, 'b': 2}, {'c': 3}) # {'a': 1, 'b': 2, 'c': 3}

敬請關注個人微信公眾號:測試工匠麻辣燙