Python字典操作函式

2021-10-08 08:33:32 字數 4131 閱讀 2990

1、鍵與值使用分號隔開→key:value

2、鍵值對使用逗號隔開→key:value,key:value

3、整個字典使用花括號包含→

使用中括號+key可以得到對應的value

>>

>

dict

=>>

>

print

(dict

['name'])

zara

>>

>

print

(dict

['age'])

7

更新字典(key/value)

>>

>

dict

=>>

>

dict

['age']=

8>>

>

print

(dict

['age'])

8>>

>

dict

['school']=

"mit"

>>

>

print

(dict

)>>

>

print

(dict

['school'])

"mit"

刪除字典(key/value)

>>

>

dict

=>>

>

deldict

['name'

]>>

>

print

(dict

)>>

>

dict

.clear(

)>>

>

print

(dict

)>>

>

deldict

>>

>

print

(dict

)<

class

'dict'

>

>>

>

print

(dict

['school'])

typeerror:

'type'

object

isnot subscriptable

4、key具有唯一性

如果key值不唯一,則後面的key/value覆蓋前面相同key對應的key/value

>>

>

dict

=>>

>

print

(dict

['name'])

'manni'

4、key不可更改

可以使用字串,數字或元組作為字典鍵,但是像[『key』]這樣的東西是不允許的

>>

>

dict

=typeerror: unhashable type

:'list'

內建函式

>>

>

dict=;

>>

>

print

(len

(dict))

2>>

>

dict

.clear(

)>>

>

print

(len

(dict))

0>>

>

print

(dict

)

>>

> dict1 =

;>>

> dict2 = dict1.copy(

)>>

>

print

(dict2)

>>

> seq =

('name'

,'age'

,'***'

)>>

>

dict

=dict

.fromkeys(seq)

>>

>

print

(dict

)>>

>

dict

=dict

.fromkeys(seq,10)

>>

>

print

(dict

)

>>

>

dict

=>>

>

print

(dict

.get(

'age'))

7

>>

>

dict

=>>

>

print

(dict

.has_key(

'age'))

true

>>

>

print

(dict

.has_key(

'***'))

false

>>

>

dict

=>>

>

print

(dict

.items())

[('age',7

),('name'

,'zara')]

>>

>

for key,value in

dict

.items():

print

("key:"

, key,

",",

"value:"

, value)

key: name , value: zara

key: age , value:

7

>>

>

dict

=>>

>

print

(dict

.keys())

dict_keys(

['name'

,'age'

])

>>

>

dict

=>>

>

print

(dict

.values())

dict_values(

['zara',7

])

>>

>

dict

=>>

>

print

(dict

.setdefault(

'age'

,none))

7>>

>

print

(dict

.setdefault(

'***'

,none))

none

>>

>

dict

=>>

> dict2 =

>>

>

dict

.update(dict2)

>>

>

print

(dict

)

控制台與jupyter notebook輸出的區別

控制台輸出——無序

jupyter notebook輸出——有序

python教程 字典函式 操作

一 字典操作 1.往字典中新增鍵值對 dict key value stu stu boy print stu setdefault 有返回值 stu stu.setdefault print stu 結果 stu stu.setdefault boy print stu 結果新增的鍵存在時 stu...

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...