在Python中,字典物件是儲存鍵(Key)/值(Value)對應的物件,為dict的實例。直接示範如何以實字建立字典物件:
>>> passwords = {'Justin' : 123456, 'caterpillar' : 933933}
>>> passwords['Justin']
123456
>>> passwords['caterpillar']
933933
>>> passwords['Hamimi'] = 970221
>>> passwords
{'caterpillar': 933933, 'Hamimi': 970221, 'Justin': 123456}
>>> passwords['Hamimi']
970221
>>> del passwords['caterpillar']
>>> passwords
{'Hamimi': 970221, 'Justin': 123456}
>>>
>>> passwords['Justin']
123456
>>> passwords['caterpillar']
933933
>>> passwords['Hamimi'] = 970221
>>> passwords
{'caterpillar': 933933, 'Hamimi': 970221, 'Justin': 123456}
>>> passwords['Hamimi']
970221
>>> del passwords['caterpillar']
>>> passwords
{'Hamimi': 970221, 'Justin': 123456}
>>>
建立字典時,每個鍵物件(在上例中是字串,也可以是任何不可變動的物件,像是數字或Tuple等)會用來取得對應的值物件,指定鍵物件取得值物件時是使用[]運算子。建立字典物件後,你可以隨時再加入鍵/值。如果要刪除某個鍵/值,則可以使用del。
直接使用[]指定鍵要取得值時,若字典中並沒有該鍵的存在,則會丟出KeyError。可以使用in來測試鍵是否存在於字典中。例如:
>>> passwords['caterpillar']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'caterpillar'
>>> if 'caterpillar' in passwords:
... print(passwords['Justin'])
... else:
... print(None)
...
None
>>> print(passwords.get('caterpillar'))
None
>>> print(passwords.get('caterpillar', 'NO_PASSWORD'))
NO_PASSWORD
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'caterpillar'
>>> if 'caterpillar' in passwords:
... print(passwords['Justin'])
... else:
... print(None)
...
None
>>> print(passwords.get('caterpillar'))
None
>>> print(passwords.get('caterpillar', 'NO_PASSWORD'))
NO_PASSWORD
>>>
上例中,也示範了字典的get()方法,使用get()方法指定的鍵若不存在,預設會傳回None,get()可以指定預設值,在指定的鍵不存在時就傳回預設值。
可以使用update()將指定的字典物件加入,使用pop()方法可以指定鍵將對應的鍵/值取出並從字典中移除。例如:
>>> passwords
{'Hamimi': 970221, 'Justin': 123456}
>>> passwords.update({'Momor' : 670723})
>>> passwords
{'Hamimi': 970221, 'Justin': 123456, 'Momor': 670723}
>>> passwords.pop('Justin')
123456
>>> passwords
{'Hamimi': 970221, 'Momor': 670723}
{'Hamimi': 970221, 'Justin': 123456}
>>> passwords.update({'Momor' : 670723})
>>> passwords
{'Hamimi': 970221, 'Justin': 123456, 'Momor': 670723}
>>> passwords.pop('Justin')
123456
>>> passwords
{'Hamimi': 970221, 'Momor': 670723}
如果要取得字典中的鍵/值,則可以使用items()方法,這會以dict_items物件,當中是以Tuple儲存每一對鍵/值。如果要取得鍵,則可以使用keys()方法,這會傳回dict_keys物件,當中包括所有的鍵。如果要取得值,則可以使用values()方法,這會傳回dict_values物件,當中包括所有的值。例如:
>>> for person in passwords:
... print(passwords[person])
...
970221
670723
>>> passwords.items()
dict_items([('Hamimi', 970221), ('Momor', 670723)])
>>> for item in passwords.items():
... print(item)
...
('Hamimi', 970221)
('Momor', 670723)
>>> passwords.keys()
dict_keys(['Hamimi', 'Momor'])
>>> for key in passwords.keys():
... print(key)
...
Hamimi
Momor
>>> list(passwords.keys())
['Hamimi', 'Momor']
>>> passwords.values()
dict_values([970221, 670723])
>>> for value in passwords.values():
... print(value)
...
970221
670723
>>> list(passwords.values())
[970221, 670723]
>>>
... print(passwords[person])
...
970221
670723
>>> passwords.items()
dict_items([('Hamimi', 970221), ('Momor', 670723)])
>>> for item in passwords.items():
... print(item)
...
('Hamimi', 970221)
('Momor', 670723)
>>> passwords.keys()
dict_keys(['Hamimi', 'Momor'])
>>> for key in passwords.keys():
... print(key)
...
Hamimi
Momor
>>> list(passwords.keys())
['Hamimi', 'Momor']
>>> passwords.values()
dict_values([970221, 670723])
>>> for value in passwords.values():
... print(value)
...
970221
670723
>>> list(passwords.values())
[970221, 670723]
>>>
實際上,items()、keys()傳回的物件具有集合(Set)的特性,可以與集合物件進行運算,values()則否,因為值不一定是唯一的(不同的鍵可能有相同的值),所以無法視為集合。例如:
>>> passwords.items() | {'x', 'y'}
{'y', ('Momor', 670723), 'x', ('Hamimi', 970221)}
>>> passwords.keys() | {'x', 'y'}
{'y', 'x', 'Hamimi', 'Momor'}
>>> passwords.values() | {'x', 'y'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'set'
>>>
{'y', ('Momor', 670723), 'x', ('Hamimi', 970221)}
>>> passwords.keys() | {'x', 'y'}
{'y', 'x', 'Hamimi', 'Momor'}
>>> passwords.values() | {'x', 'y'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'set'
>>>
除了實字表示方式之外,你也可以使用dict來建立字典。例如:
>>> passwords = dict(justin = 123456, momor = 670723, hamimi = 970221)
>>> passwords
{'hamimi': 970221, 'justin': 123456, 'momor': 670723}
>>> passwords = dict([('justin', 123456), ('momor', 670723), ('hamimi', 970221)])
>>> passwords
{'hamimi': 970221, 'justin': 123456, 'momor': 670723}
>>> dict.fromkeys(['Justin', 'momor'], 'NEED_TO_CHANGE')
{'Justin': 'NEED_TO_CHANGE', 'momor': 'NEED_TO_CHANGE'}
>>>
>>> passwords
{'hamimi': 970221, 'justin': 123456, 'momor': 670723}
>>> passwords = dict([('justin', 123456), ('momor', 670723), ('hamimi', 970221)])
>>> passwords
{'hamimi': 970221, 'justin': 123456, 'momor': 670723}
>>> dict.fromkeys(['Justin', 'momor'], 'NEED_TO_CHANGE')
{'Justin': 'NEED_TO_CHANGE', 'momor': 'NEED_TO_CHANGE'}
>>>