標籤:python
字典是python中唯一的映射類型,採用索引值對(key-value)的形式儲存資料。python對key進行雜湊函數運算,根據計算的結果決定value的儲存地址,所以字典是無序儲存的,且key必須是可雜湊的。可雜湊表示key必須是不可變類型,如:數字、字串、元組。
字典(dictionary)是除列表意外python之中最靈活的內建資料結構類型。列表是有序的對象結合,字典是無序的對象集合。兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過位移存取。
建立字典:
= {::}shop2 = ((()))()(shop2)
輸出:
{‘iphone‘: 2000, ‘book‘: ‘python‘}
{‘iphone7s‘: ‘new‘}
對應操作:
1、增
= {}[] = [] = ()shop1 = .setdefault()(shop1)shop2 = .setdefault()(shop2)()
輸出:
{‘iphone7s‘: ‘new‘, ‘price‘: 8000}
8000
JD
{‘iphone7s‘: ‘new‘, ‘price‘: 8000, ‘buy‘: ‘JD‘}
2、查
= {: : : }(.items())(.keys())(.values())([])(.get())(.get())()((.values()))
輸出:
dict_items([(‘iphone7s‘, ‘new‘), (‘price‘, 8000), (‘buy‘, ‘JD‘)])
dict_keys([‘iphone7s‘, ‘price‘, ‘buy‘])
dict_values([‘new‘, 8000, ‘JD‘])
JD
JD
False
True
[‘new‘, 8000, ‘JD‘]
3、改
= {: : : }[] = shop1 = {::}.update(shop1)()
輸出:
{‘iphone7s‘: ‘old‘, ‘price‘: 8000, ‘buy‘: ‘JD‘, ‘iphone5‘: ‘True‘, ‘size‘: 500}
4、刪
shop = {‘iphone7s‘: ‘old‘, ‘price‘: 8000, ‘buy‘: ‘JD‘, ‘iphone5‘: ‘True‘, ‘size‘: 500}del shop[‘size‘]#刪除字典中指定索引值對print(shop)shop1 = shop.pop(‘iphone5‘)#刪除字典中指定索引值對,並返回該索引值對的值print(shop1)print(shop)shop2 = shop.popitem()#隨機刪除某組索引值對,並以元組方式傳回值print(shop2)print(shop)shop.clear()# 清空字典print(shop)
輸出:
{‘iphone7s‘: ‘old‘, ‘price‘: 8000, ‘buy‘: ‘JD‘, ‘iphone5‘: ‘True‘}
True
{‘iphone7s‘: ‘old‘, ‘price‘: 8000, ‘buy‘: ‘JD‘}
(‘buy‘, ‘JD‘)
{‘iphone7s‘: ‘old‘, ‘price‘: 8000}
{}
5、內建方法
dict.fromkeys
=.fromkeys([])()[]=()=.fromkeys([][])()[][]=()
輸出:
{‘host1‘: ‘test‘, ‘host2‘: ‘test‘, ‘host3‘: ‘test‘}
{‘host1‘: ‘test‘, ‘host2‘: ‘abc‘, ‘host3‘: ‘test‘}
{‘host1‘: [‘test1‘, ‘tets2‘], ‘host2‘: [‘test1‘, ‘tets2‘], ‘host3‘: [‘test1‘, ‘tets2‘]}
{‘host1‘: [‘test1‘, ‘test3‘], ‘host2‘: [‘test1‘, ‘test3‘], ‘host3‘: [‘test1‘, ‘test3‘]}
={:::}()((.items()))
輸出:
True
[(2, ‘666‘), (4, ‘444‘), (5, ‘555‘)]
={: : }i : (i[i])iv .items(): (iv)item .items(): (item)
輸出:
name joker
age 18
name joker
age 18
(‘name‘, ‘joker‘)
(‘age‘, 18)
本文出自 “on_the_road” 部落格,請務必保留此出處http://cqtesting.blog.51cto.com/8685091/1958821
python學習筆記字典(四)