鍵在一個(gè)字典中是唯一的,而值則可以重復(fù)。字典的值可以是任何類型,但鍵必須是不可變的數(shù)據(jù)的類型,例如:字符串,數(shù)字或元組這樣的類型。
要訪問字典元素,你可以使用方括號(hào)和對(duì)應(yīng)鍵,以獲得其對(duì)應(yīng)的值。下面是一個(gè)簡(jiǎn)單的例子 -
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
dict['Name']: Zara dict['Age']: 7
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice']
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
dict['Age']: 8 dict['School']: DPS School
可以刪除單個(gè)字典元素或清除字典的全部?jī)?nèi)容。也可以在一個(gè)單一的操作刪除整個(gè)詞典。
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
字典的值沒有限制。它們可以是任意Python對(duì)象,無論是標(biāo)準(zhǔn)的對(duì)象或用戶定義的對(duì)象。但是,鍵卻不能這樣使用。
(一)每個(gè)鍵對(duì)應(yīng)多個(gè)條目是不允許的。這意味著重復(fù)鍵是不允許的。當(dāng)鍵分配過程中遇到重復(fù),以最后分配的為準(zhǔn)。例如 -
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
dict['Name']: Manni
(二)鍵必須是不可變的。這意味著可以使用字符串,數(shù)字或元組作為字典的鍵,但是像['key']是不允許的。下面是一個(gè)簡(jiǎn)單的例子:
#!/usr/bin/python3
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
當(dāng)執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable
| SN |
函數(shù)與描述
|
|---|---|
| 1 |
比較這兩個(gè)字典的元素。
|
| 2 |
計(jì)算字典的總長(zhǎng)度。這等于字典中的項(xiàng)的數(shù)目。
|
| 3 |
產(chǎn)生字典的可打印字符串表示
|
| 4 |
返回傳遞變量的類型。如果傳遞變量是字典,那么它會(huì)返回一個(gè)字典類型。 |
| SN |
描述與方法
|
|---|---|
| 1 |
刪除字典 dict 中的所有元素
|
| 2 |
返回字典 dict 的淺表副本
|
| 3 |
使用seq的鍵和值來設(shè)置創(chuàng)建新字典
|
| 4 |
對(duì)于鍵key,返回其值或default如果鍵不存在于字典中
|
| 5 |
返回true如果在字典dict有存在鍵key,否則為false
|
| 6 |
返回 dict (鍵,值)元組對(duì)的列表
|
| 7 |
返回字典 dict 的鍵列表
|
| 8 |
dict.setdefault(key, default=None)
類似于get()方法,但會(huì)設(shè)定dict[key]=default,如果鍵不存在于dict中
|
| 9 |
添加字典dict2的鍵值對(duì)到dict
|
| 10 |
返回字典dict值列表
|