字典是python中唯一的映射類型,採用鍵值對(key-value)的形式存儲數據。python對key進行哈希函數運算,根據計算的結果決定value的存儲地址,所以字典是無序存儲的,且key必須是可哈希的。可哈希表示key必須是不可變類型,如:數字、字符串、元組。
字典(dictionary)是除列表意外python之中最靈活的內置數據結構類型。列表是有序的對象結合,字典是無序的對象集合。兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。
創建字典:
shop = {'iphone':2000,'book':'python'} shop2 = dict((('iphone7s','new'),)) print(shop) print(shop2)
輸出:
{'iphone': 2000, 'book': 'python'}
{'iphone7s': 'new'}
對應操作:
1、增
shop = {} shop['iphone7s'] = 'new' shop['price'] = 8000 print(shop) shop1 = shop.setdefault('price',9000)#鍵存在,不改動,返回字典中相應的鍵對應的值 print(shop1) shop2 = shop.setdefault('buy','JD')#鍵不存在,在字典中中增加新的鍵值對,並返回相應的值 print(shop2) print(shop)
輸出:
{'iphone7s': 'new', 'price': 8000}
8000
JD
{'iphone7s': 'new', 'price': 8000, 'buy': 'JD'}
2、查
shop = {'iphone7s': 'new', 'price': 8000, 'buy': 'JD'} print(shop.items()) print(shop.keys()) print(shop.values()) print(shop['buy']) print(shop.get('buy',False)) print(shop.get('buys',False)) print('buy' in shop) print(list(shop.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、改
shop = {'iphone7s': 'new', 'price': 8000, 'buy': 'JD'} shop['iphone7s'] = 'old' shop1 = {'iphone5':'True','size':500} shop.update(shop1) print(shop)
輸出:
{'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
dic6=dict.fromkeys(['host1','host2','host3'],'test') print(dic6) dic6['host2']='abc' print(dic6) dic6=dict.fromkeys(['host1','host2','host3'],['test1','tets2']) print(dic6) dic6['host2'][1]='test3' print(dic6)
輸出:
{'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']}
dic={5:'555',2:'666',4:'444'} print(5 in dic) print(sorted(dic.items()))
輸出:
True
[(2, '666'), (4, '444'), (5, '555')]
dic5={'name': 'joker', 'age': 18} for i in dic5: print(i,dic5[i]) for i,v in dic5.items(): print(i,v) for item in dic5.items(): print(item)
輸出:
name joker
age 18
name joker
age 18
('name', 'joker')
('age', 18)
補充:字典與字符串相互轉換:
字典轉換爲字符串
a = {'a' : 1, 'b' : 2, 'c' : 3} b = str(a) print(type(b))
<class 'str'>輸出結果爲:
---------------------------------------------------------------
字符串轉換爲字典
a = "{'a' : 1, 'b' : 2, 'c' : 3}" b = eval(a) print(type(b))
<class 'dict'>輸出結果爲: