1. 字典及其創(chuàng)建
在Python中,字典是一系列鍵—值對(duì)。每個(gè)鍵都與一個(gè)值相關(guān)聯(lián),值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串,數(shù)字或元組。
字典的創(chuàng)建方法常用花括號(hào)生成也可以使用函數(shù)dict()創(chuàng)建。
# 字典的創(chuàng)建,使用花括號(hào){}
scores = {'張三': 100, '李四': 99, '王五': 98}
print(scores)
# 使用內(nèi)置函數(shù)dict()
student = dict(czh=100)
print(student)
# 空字典{}
d = {}
print(d)
2. 字典元素的獲取
字典元素的獲取常用鍵來(lái)獲取或者使用get()函數(shù)獲取。
# 字典元素的獲取
# 第一種方式,使用[]
scores = {'張三': 100, '李四': 99, '王五': 98}
print(scores['張三'])
# 第二種方式,使用get()方法
print(scores.get('張三'))
print(scores.get('陳六', 99)) # 99是在查找不存在時(shí)提供的一個(gè)默認(rèn)值
3. 字典元素的刪除與清空
刪除字典元素使用del。
# 字典元素的刪除
del scores['張三'] # 刪除指定的key-value對(duì)
print(scores)
清空字典用clear()。
# 字典元素的清空 clear()
scores.clear()
print(scores)
4. 字典元素的增加
字典元素的增加是直接對(duì)字典新增鍵值對(duì)。
# 字典元素的增加
scores = {'張三': 100, '李四': 99, '王五': 98}
print(scores)
scores['陳六'] = 98
print(scores)
5. 字典元素的修改
字典元素的增加是通過(guò)鍵對(duì)值修改。
# 字典元素的修改
scores['陳六'] = 100
print(scores)
6. 字典的鍵、值和鍵值對(duì)的獲取
獲取字典中所有的鍵。
# 獲取所有的鍵
keys = scores.keys()
print(keys)
print(type(keys))
print(list(keys)) # 將所有的鍵轉(zhuǎn)換成列表
獲取字典中所有的值。
# 獲取所有的值
values = scores.values()
print(values)
print(type(values))
print(list(values))
# 獲取所有的鍵值對(duì)
items = scores.items()
print(items)
print(type(items))
print(list(items))
7. 字典元素的遍歷
# 字典元素的遍歷
scores = {'張三': 100, '李四': 99, '王五': 98}
for i in scores:
print(i, scores[i], scores.get(i))
8. 字典的特點(diǎn)
字典中所有的元素都是一個(gè)鍵值對(duì),key不允許重復(fù),值可以重復(fù)。
# 字典的特點(diǎn)
# 字典中所有的元素都是一個(gè)鍵值對(duì),key不允許重復(fù),值可以重復(fù)
s = {'張二': 99, '張二': 100}
print(s) # 如果鍵重復(fù),將會(huì)覆蓋{'張二': 100}
s1 = {'張二': 100, '張三': 100} # 值可以重復(fù)
print(s1)
# 字典元素是無(wú)序的
# 字典中的key必須是不可變對(duì)象,比如字符串
9. 字典生成式
字典的快速生成用zip()函數(shù)實(shí)現(xiàn)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-474255.html
# 字典生成式
# 內(nèi)置函數(shù)zip()
i = ['aaa', 'bbb', 'ccc']
j = [99, 98, 100]
A = {i:j for i, j in zip(i, j)}
print(A)
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-474255.html
到了這里,關(guān)于python基礎(chǔ)知識(shí)(八):字典的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!