Python3字典是一種可變容器模型,它存儲的是鍵值對,鍵是獨一無二的,而值可以是任何數據類型。它非常適合存儲一些具有內在聯繫的數據。
一、從Python3字典取值
訪問Python3字典中的數值是通過鍵來完成的。為了獲取字典中的值,可以使用以下方式:
dict1 = {'name': 'John', 'age': 30, 'gender': 'Male'} print(dict1['name'])
這裡的dict1是Python3字典對象,name, age以及gender是鍵。輸出結果是John。
在Python3中,還可以使用get()方法來獲取字典中的數值:
print(dict1.get('age'))
輸出結果是30。使用get()方法獲取字典中的數值可以避免一些由於使用不存在的鍵而導致的運行時錯誤。
二、Python3字典類型刪除
刪除Python3字典對象有多種方法。最基本的是使用del語句:
dict2 = {'name': 'Tom', 'age': 25, 'gender': 'Female'} del dict2['gender'] print(dict2)
這個例子中,del語句刪除了字典中的gender鍵,輸出結果是{‘name’: ‘Tom’, ‘age’: 25}。
如果要刪除整個字典對象,可以使用del語句:
del dict2 #print(dict2) 如果這樣運行代碼會提示變數未定義
三、Python3字典刪除
使用pop()方法可以刪除指定的鍵值對,並返回刪除的值:
dict3 = {'name': 'Lucy', 'age': 25, 'gender': 'Female'} print(dict3.pop('gender')) print(dict3)
輸出結果是:
Female {'name': 'Lucy', 'age': 25}
在以上示例中,pop()方法用於刪除了字典對象中的gender鍵並返回其值。
四、Python3字典合併
在Python3中,可以使用update()方法將兩個字典對象合併:
dict4 = {'name': 'Lily', 'age': 22} dict5 = {'gender': 'Female'} dict4.update(dict5) print(dict4)
輸出結果是:
{'name': 'Lily', 'age': 22, 'gender': 'Female'}
五、Python3字典 菜鳥
Python3字典創建可以使用{}或者dict()方法,基本操作使用鍵名訪問。具體請看如下代碼示例:
dict6 = {'foo': 'bar', 'hello': 'world', 'name': 'Mike'} print(dict6) dict7 = dict(foo='bar2', hello='world2',name='Mike2') print(dict7) print(dict7['name'])
輸出結果是:
{'foo': 'bar', 'hello': 'world', 'name': 'Mike'} {'foo': 'bar2', 'hello': 'world2', 'name': 'Mike2'} Mike2
六、Python3字典刪除鍵值對
pop()方法可以刪除指定的鍵值對,而popitem()則是隨機刪除鍵值對:
dict8 = {'name': 'Tim', 'age': 25, 'gender': 'Male'} dict8.pop('age') print(dict8) dict8.popitem() print(dict8)
輸出結果是:
{'name': 'Tim', 'gender': 'Male'} {'name': 'Tim'}
七、Python3字典用法
Python3字典還可以用來實現一些高級功能,例如計數器:
from collections import Counter list1 = ['a', 'b', 'a', 'c', 'c', 'a'] print(Counter(list1))
輸出結果是:
Counter({'a': 3, 'c': 2, 'b': 1})
八、Python3字典修改
修改一個已有的鍵的值可以通過賦值運算符完成:
dict9 = {'name': 'Lucy', 'age': 25, 'gender': 'Female', 'address': '123 Main St'} dict9['address'] = '456 Oak St' print(dict9)
輸出結果是:
{'name': 'Lucy', 'age': 25, 'gender': 'Female', 'address': '456 Oak St'}
九、Python3字典怎麼換行輸出
可以使用pprint模塊中的pprint()方法來換行輸出Python3字典:
import pprint dict10 = {'name': 'Jack', 'age': 25, 'gender': 'Male', 'address': '789 Park Ave'} pprint.pprint(dict10, width=1)
輸出結果是:
{'address': '789 Park Ave', 'age': 25, 'gender': 'Male', 'name': 'Jack'}
在pprint()方法中,width參數控制輸出文本的寬度。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257812.html