python 字典操作

2021-09-22 10:46:18 字數 1192 閱讀 4579

假設字典為dics =

1.從字典中取值,當鍵不存在時不想處理異常

[方法]  dics.get('key', 'not found')

[例如]

[解釋] 當鍵'key'不存在是,列印'not found'(即想要處理的資訊),當存在是輸出鍵值。

【其他解決方案一】

if key in

dics:

print

dics[key]

else

:

print

'not found!!

'

【其他解決方案二】

try

:

print

dics[key]

except

keyerror:

print

'not found

'

例子:

2.從字典中取值,若找到則刪除;當鍵不存在時不想處理異常

[方法]  dics.pop('key', 'not found')

[例如]

[解釋] 當鍵'key'不存在是,列印'not found'(即想要處理的資訊),當存在是輸出鍵值,並且去除該健。

3.給字典新增乙個條目。如果不存在,就指定特定的值;若存在,就算了。

[方法] dic.setdefault(key, default)

[例如]

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.訪問和訪問...