1. 程式人生 > 實用技巧 >Python基本語法總結(五)字典操作

Python基本語法總結(五)字典操作

訪問字典中的值

要獲取與鍵相關聯的值,可依次指定字典名和放在方括號內的鍵,如下所示:

>>> dict={'color':'green'}
>>> print(dict['color'])    # 利用鍵訪問值
green
>>> 

新增鍵-值對

字典是一種動態結構,可隨時在其中新增鍵—值對。要新增鍵—值對,可依次指定字典名、用方括號括起的鍵和相關聯的值。

>>> dict={'color':'green'}
>>> dict['point']=5 # 直接新增鍵-值對
>>> dict['x_pos']=0
>>> dict['y_pos']=25
>>> print(dict)
{'color': 'green', 'point': 5, 'x_pos': 0, 'y_pos': 25}
>>> 

修改字典中的值

要修改字典中的值,可依次指定字典名、用方括號括起的鍵以及與該鍵相關聯的新值。

>>> dict={'color':'green'}
>>> print(dict)
{'color': 'green'}
>>> dict['color']='yellow'  # 字典名[鍵] = 修改值
>>> print(dict)
{'color': 'yellow'}
>>> 

刪除字典中的鍵-值對

對於字典中不再需要的資訊,可使用del語句將相應的鍵—值對徹底刪除。使用del語句時,必須指定字典名和要刪除的鍵。

>>> alien_0 = {'color': 'green', 'points': 5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> del alien_0['points']   # 利用del刪除鍵-值對
>>> print(alien_0)
{'color': 'green'}
>>> 

遍歷字典

可以使用一個for迴圈來遍歷這個字典:

>>> user_0 = { 
    'username': 'efermi', 
    'first': 'enrico', 
    'last': 'fermi', 
    }
>>> for key,value in user_0.items():    # items()返回一個鍵值對列表,for迴圈依次將每個鍵值對儲存到兩個變數中
	print('Key:',key)
	print('Vaule:',value)

Key: username   # 返回順序可能與儲存順序不同
Vaule: efermi
Key: first
Vaule: enrico
Key: last
Vaule: fermi
>>> 

由於字典返回的元素在字典中的順序不定,為了以特定的順序返回元素,可以利用sorted()函式獲得排序後的字典的副本再訪問:

>>> favorite_languages = { 
    'jen': 'python', 
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'python', 
    }
>>> for name in sorted(favorite_languages.keys()): 
	    print(name.title() + ", thank you for taking the poll.")
	    
Edward, thank you for taking the poll.  # 按照ascii碼順序
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
>>> 

如果想要檢視字典中所有的鍵而不檢視對應的值,可以利用方法keys():

>>> favorite_languages = { 
    'jen': 'python', 
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'c#', 
    }
>>> for name in favorite_languages.keys():
	print(name)
	
jen
sarah
edward
phil
>>> 

同理,想要只訪問字典中的所有值,可以利用方法values():

>>> favorite_languages = { 
    'jen': 'python', 
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'c#', 
    }
>>> for value in favorite_languages.values():
	print(value)
	
python
c
ruby
c#
>>> 

由於在字典中鍵是唯一不可重複的,而值可能重複,故若想知道值的種類(去重後),可以使用集合set,通過對包含重複元素的列表呼叫set(),可讓Python找出列表中獨一無二的元素,並使用這些元素建立一個集合:

>>> favorite_languages = { 
    'jen': 'python', 
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'c#',
    'bob':'c',
    'john':'python'
    }
>>> for value in set(favorite_languages.values()):
	print(value)

python  # 去重後
ruby
c#
c
>>> 

判斷某個鍵是否存在於字典中

if key in dict.keys():
    ...