python字典操作

2021-10-14 13:39:31 字數 2615 閱讀 4207

字典:python內建的資料結構之一,與列表一樣是乙個可變序列,以鍵值對的方式儲存資料,字典是乙個無序的列表。

1.使用花括號{}

2.使用內建函式dict()

#{}建立字典

score =

print

(score)

#dict()建立字典

bag =

dict

(pen =

3,roller =

4, eraser =2)

print

(bag)

3.建立空字典

d =

1.字典名[鍵]

2.字典名.get(鍵)

取值和get()取值的區別:

get()方法取值,如果字典中不存在指定的key,並不會丟擲keyerror而是返回none,可以通過引數設定預設的value,以便指定的key不存在時返回。

#

scores =

print

(scores[

'張三'])

#get()

print

(scores.get(

'張三'))

#返回none

print

(scores.get(

'王五'))

#20查詢不存在時返回的預設值

print

(scores.get(

'王五',20

))

1.key的判斷:

in:指定的key在字典中返回true

not in:指定的key不在字典中返回true

scores =

print

('張三'

in scores)

print

('李四'

notin scores)

2.字典的刪除

#刪除指定的鍵值對

scores =

del scores[

'張三'

]print

(scores)

# 清空字典中的元素

scores.clear(

)print

(scores)

3.字典元素的新增

#新增元素

scores =

scores[

'孫大聖']=

100

4.字典元素修改

scores =

scores[

'張三']=

0

1.獲取字典檢視

①keys():獲取字典中所有key

②values():獲取字典中所有value

③items():獲取字典中所有key,value對

#獲取所有key

keys = scores.keys(

)print

(keys)

print

(type

(keys)

)print

(list

(keys)

)#將所有的key組成的檢視轉成列表

#獲取所有的value

values = scores.values(

)print

(values)

print

(type

(values)

)print

(list

(values)

)#獲取所有的鍵值對

items = scores.items(

)print

(items)

#轉換之後的列表是由元組組成的

print

(type

(items)

)print

(list

(items)

)

2.字典元素的遍歷

scores =

for item in scores:

print

(item,scores[item]

,scores.get(item)

)

內建函式zip():用於將可迭代的物件作為引數,將物件中對應的元素打包成乙個元組,然後返回由這些元組組成的列表。

可迭代物件:可以使用for in迴圈遍歷的物件

fruits =[,

'pear'

,'peach'

,'grape'

]prices =[5

,3,4

]d =

print

(d)

在打包zip()的過程中,會以key或value中元素少的一方為基準。

字典中的所有元素都是乙個key-value對,key不允許重複,value可以重複

字典中的元素是無序的

字典中的key必須是不可變物件

字典也可以根據需要動態地伸縮

字典會浪費較大的記憶體,是一種使用空間換時間的資料結構

python操作字典 Python 字典操作高階

學習了 python 基本的字典操作後,學習這些高階操作,讓寫出的 更加優雅簡潔和 pythonic 與字典值有關的計算 問題想對字典的值進行相關計算,例如找出字典裡對應值最大 最小 的項。解決方案一 假設要從字典 中找出值最小的項,可以這樣做 d min zip d.values d.keys 2...

python 字典操作

python 語法之字典 2009 10 21 磁針石 xurongzhong gmail.com 部落格 oychw.cublog.cn python essential reference 4th edition 2009 beginning python from novice to prof...

python 字典操作

1 什麼是字典?字典是python語言中唯一的對映型別。對映型別物件裡雜湊值 鍵,key 和指向的物件 值,value 是一對多的的關係,通常被認為是可變的雜湊表。字典物件是可變的,它是乙個容器型別,能儲存任意個數的python物件,其中也可包括其他容器型別。字典型別與序列型別的區別 1.訪問和訪問...