python字典
字典(英文名 dict),它是由一系列的鍵值(key-value)對組合而成的數(shù)據(jù)結(jié)構(gòu)。
字典中的每個鍵都與一個值相關(guān)聯(lián),其中
鍵,必須是可 hash 的值,如字符串,數(shù)值等
值,則可以是任意對象
1. 創(chuàng)建字典
創(chuàng)建一個字典有三種方法
第一種方法:先使用 dict()
創(chuàng)建空字典實(shí)例,再往實(shí)例中添加元素
>>> profile = dict(name="張三", age=18)
>>> profile
{'name': '張三', 'age': 18}
第二種方法:直接使用 {}
定義字典,并填充元素。
>>> profile = {"name": "張三", "age": 18}
>>> profile
{'name': '張三', 'age': 18}
第三種方法:使用 dict()
構(gòu)造函數(shù)可以直接從鍵值對序列里創(chuàng)建字典。
>>> info = [('name', '張三'), ('age', 18)]
>>> dict(info)
{'name': '張三', 'age': 18}
第四種方法:使用字典推導(dǎo)式,這一種對于新手來說可能會比較難以理解,我會放在后面專門進(jìn)行講解,這里先作了解,新手可直接跳過。
>>> adict = {x: x**2 for x in (2, 4, 6)}
>>> adict
{2: 4, 4: 16, 6: 36}
2. 增刪改查
增刪改查:是 新增元素、刪除元素、修改元素、查看元素的簡寫。
由于,內(nèi)容比較簡單,讓我們直接看演示
查看元素
查看或者訪問元素,直接使用 dict[key]
的方式就可以
>>> profile = {"name": "張三", "age": 18}
>>> profile["name"]
'張三'
但這種方法,在 key 不存在時會報 KeyValue 的異常
>>> profile = {"name": "張三", "age": 18}
>>> profile["gender"]
Traceback (most recent call last):
File "", line 1, in
KeyError: 'gender'
所以更好的查看獲取值的方法是使用 get()
函數(shù),當(dāng)不存在 gender 的key時,默認(rèn)返回 male
>>> profile = {"name": "張三", "age": 18}
>>> profile.get("gender", "male")
'male'
新增元素
新增元素,直接使用 dict[key] = value
就可以
>>> profile = dict()
>>> profile
{}
>>> profile["name"] = "張三"
>>> profile["age"] = 18
>>> profile
{'name': '張三','age': 18}
修改元素
修改元素,直接使用 dict[key] = new_value
就可以
>>> profile = {"name": "張三", "age": 18}
>>> profile["age"] = 28
>>> profile
{'name': '張三', 'age': 28}
刪除元素
刪除元素,有三種方法
第一種方法:使用 pop 函數(shù)
>>> profile = {"name": "張三", "age": 18}
>>> profile.pop("age")
18
>>> profile
{'name': '張三'}
第二種方法:使用 del 函數(shù)
>>> profile = {"name": "張三", "age": 18}
>>> del profile["age"]
>>> profile
{'name': '張三'}
3. 重要方法
判斷key是否存在
在 Python 2 中的字典對象有一個 has_key 函數(shù),可以用來判斷一個 key 是否在該字典中
>>> profile = {"name": "張三", "age": 18}
>>> profile.has_key("name")
True
>>> profile.has_key("gender")
False
但是這個方法在 Python 3 中已經(jīng)取消了,原因是有一種更簡單直觀的方法,那就是使用 in
和 not in
來判斷。
>>> profile = {"name": "張三", "age": 18}
>>> "name" in profile
True
>>> "gender" in profile
False
設(shè)置默認(rèn)值
要給某個 key 設(shè)置默認(rèn)值,最簡單的方法
profile = {"name": "張三", "age": 18}
if "gender" not in profile:
profile["gender"] = "male"
實(shí)際上有個更簡單的方法
profile = {"name": "張三", "age": 18}
profile.setdefault("gender", "male")
審核編輯:符乾江
-
字典
+關(guān)注
關(guān)注
0文章
13瀏覽量
7756 -
python
+關(guān)注
關(guān)注
56文章
4821瀏覽量
85776
發(fā)布評論請先 登錄
相關(guān)推薦
python入門圣經(jīng)-高清電子書(建議下載)
零基礎(chǔ)入門:如何在樹莓派上編寫和運(yùn)行Python程序?

評論