python小白之字典使用筆記

來源:互聯網
上載者:User

標籤:技術   clear   條目   冒號   不可變   usr   image   man   alt   

 

Python 字典(Dictionary)

  字典是一種可變容器模型,且可儲存任意類型對象。

每個索引值 key=>value 對,用冒號 : 分割

每個索引值對之間用逗號 , 分割

整個字典包括在花括弧 {} 中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

 建立 

>>>dict = {‘a‘: 1, ‘b‘: 2, ‘b‘: ‘3‘};>>> dict[‘b‘]‘3‘>>> dict{‘a‘: 1, ‘b‘: ‘3‘}

訪問

#!/usr/bin/python dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}; print "dict[‘Name‘]: ", dict[‘Name‘];print "dict[‘Age‘]: ", dict[‘Age‘];

輸出

 

修改

dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}; dict[‘Age‘] = 8; # update existing entrydict[‘School‘] = "DPS School"; # Add new entry  print "dict[‘Age‘]: ", dict[‘Age‘];print "dict[‘School‘]: ", dict[‘School‘];

輸出

刪除

 dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}; del dict[‘Name‘]; # 刪除鍵是‘Name‘的條目dict.clear();     # 清空詞典所有條目del dict ;        # 刪除詞典

 

字典的特徵:

不允許同一個鍵出現兩次。建立時如果同一個鍵被賦值兩次,後一個值會被記住,如下執行個體:

dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Name‘: ‘Manni‘}; print "dict[‘Name‘]: ", dict[‘Name‘];

只輸出後一個Manni

鍵必須不可變,所以可以用數字,字串或元組充當,所以用列表就不行,如下執行個體:

dict = {[‘Name‘]: ‘Zara‘, ‘Age‘: 7}; print "dict[‘Name‘]: ", dict[‘Name‘];

 

 

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.