python學習筆記字典(四)

來源:互聯網
上載者:User

標籤: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學習筆記字典(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.