日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢(xún)
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
Python字典

字典是一個(gè)無(wú)序的集合,包含用逗號(hào)分隔的花括號(hào)內(nèi)的key:value對(duì)。 字典經(jīng)過(guò)優(yōu)化,可以在已知關(guān)鍵字的情況下檢索值。

下面聲明一個(gè)字典對(duì)象。

Example: Dictionary

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

上圖,capitals是一個(gè)字典對(duì)象,其中包含{ }內(nèi)部的鍵值對(duì)。 左側(cè):為按鍵,右側(cè)為數(shù)值。 密鑰應(yīng)該是唯一且不可變的對(duì)象。數(shù)字、字符串或元組可以用作關(guān)鍵字。因此,以下詞典也有效:

Example: Dictionary Objects

d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value 

但是,以列表作為關(guān)鍵字的字典是無(wú)效的,因?yàn)榱斜硎强勺兊?

Error: List as Dict Key

dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

但是,列表可以用作值。

Example: List as Dictionary Value

dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]} 

同一個(gè)鍵在集合中不能出現(xiàn)多次。如果該密鑰出現(xiàn)多次,將只保留最后一次。該值可以是任何數(shù)據(jù)類(lèi)型。一個(gè)值可以分配給多個(gè)鍵。

Example: Unique Keys

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"} 

dict是所有字典的類(lèi),如下圖所示。

Example: Distinct Type

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
 

也可以使用 dict() 構(gòu)造器方法創(chuàng)建字典。

Example: dict() Constructor Method

>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'} 

訪問(wèn)字典

字典是一個(gè)無(wú)序的集合,因此不能使用索引訪問(wèn)值;相反,必須在方括號(hào)中指定一個(gè)鍵,如下所示。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals["usa"]  # Error: Key is case-sensitive
Traceback (most recent call last):
  File "", line 1, in 
    capitals['usa']
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "", line 1, in 
capitals['Japan']
KeyError: 'Japan' 

*Note:*Keys are case-sensitive. So, usa and USA are treated as different keys. If the specified key does not exist then it will raise an error. *使用 get() 方法檢索鍵的值,即使鍵是未知的。 如果密鑰不存在,則返回None,而不是產(chǎn)生錯(cuò)誤。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'Washington DC'
>>> capitals.get("France")
'Paris'
>>> capitals.get("usa")
>>> capitals.get("Japan")
>>> 

使用 for循環(huán)訪問(wèn)字典

使用 for循環(huán)迭代 Python 腳本中的字典。

Example: Access Dictionary Using For Loop

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 

Output

Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'        
Key = 'India', Value = 'New Delhi' 

更新詞典

如前所述,密鑰不能出現(xiàn)多次。使用相同的鍵并為其分配新值,以更新字典對(duì)象。

Example: Update Value of Key

>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India'] = 'Virat'
>>> captains['Australia'] = 'Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'} 

使用新的鍵并為其賦值。字典將在其中顯示一個(gè)額外的鍵值對(duì)。

Example: Add New Key-Value Pair

>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'} 

從字典中刪除值

使用 del 關(guān)鍵字、 pop() 或 popitem() 方法從字典或字典對(duì)象本身中刪除一對(duì)。要?jiǎng)h除一對(duì),請(qǐng)使用其鍵作為參數(shù)。 要?jiǎng)h除字典對(duì)象,請(qǐng)使用其名稱(chēng)。

Example: Delete Key-Value

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> del captains['Srilanka'] # deletes a key-value pair
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
>>> del captains # delete dict object
>>> captains
NameError: name 'captains' is not defined 

NameError表示字典對(duì)象已經(jīng)從內(nèi)存中移除。

檢索字典鍵和值

鍵()和值()方法分別返回包含鍵和值的視圖對(duì)象。

Example: keys()

>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg']) 

檢查字典鍵

您可以使用innot in關(guān)鍵字檢查字典集合中是否存在主鍵,如下所示。 注意,它只檢查鍵,不檢查值。

Example: Check Keys

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
True
>>> 'India' in captains
True
>>> 'France' in captains
False
>>> 'USA' not in captains
True 

多維詞典

讓我們假設(shè)有三個(gè)字典對(duì)象,如下所示:

Example: Dictionary

>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70} 

讓我們給這些學(xué)生分配卷號(hào),創(chuàng)建一個(gè)以卷號(hào)為關(guān)鍵字的多維字典,并根據(jù)它們的值對(duì)上述字典進(jìn)行排序。

Example: Multi-dimensional Dictionary

>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}< 

student對(duì)象是一個(gè)二維字典。這里d1、d2d3分別被指定為鍵 1、2 和 3 的值。students[1]返回d1。

Example: Access Multi-dimensional Dictionary

>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']
25 

內(nèi)置字典方法

方法 描述
dict.clear() 從字典中移除所有鍵值對(duì)。
dict.copy() 返回字典的一個(gè)簡(jiǎn)單副本。
發(fā)布 fromkeys() 從給定的可迭代表(字符串、列表、集合、元組)創(chuàng)建一個(gè)新的字典作為鍵,并使用指定的值。
dict.get() 返回指定鍵的值。
dict.items() 返回字典視圖對(duì)象,該對(duì)象以鍵值對(duì)列表的形式提供字典元素的動(dòng)態(tài)視圖。當(dāng)字典改變時(shí),這個(gè)視圖對(duì)象也隨之改變。
dict . key() 返回包含字典鍵列表的字典視圖對(duì)象。
dict.pop() 移除鍵并返回其值。如果字典中不存在某個(gè)鍵,則返回默認(rèn)值(如果指定的話),否則將引發(fā)鍵錯(cuò)誤。
關(guān)閉。潑皮() 從字典中移除并返回(鍵、值)對(duì)的元組。成對(duì)按后進(jìn)先出(后進(jìn)先出)順序返回。
dict.setdefault() 返回字典中指定鍵的值。如果找不到該鍵,則添加具有指定 defaultvalue 的鍵。如果未指定默認(rèn)值,則設(shè)置為無(wú)值。
dict.update() 使用來(lái)自另一個(gè)字典或另一個(gè)表(如具有鍵值對(duì)的元組)的鍵值對(duì)更新字典。
字典值() 返回字典視圖對(duì)象,該對(duì)象提供字典中所有值的動(dòng)態(tài)視圖。當(dāng)字典 改變時(shí),這個(gè)視圖對(duì)象改變。

網(wǎng)站題目:Python字典
鏈接分享:http://www.5511xx.com/article/cdijgcd.html