python資料類型——字典

來源:互聯網
上載者:User

標籤:python

引入
  • 沒有字典的時候我們可能會這麼做:
>>> t = [‘name‘, ‘age‘, ‘sex‘]>>> v = [‘chen‘, 24, ‘male‘]>>> zip(t,v)[(‘name‘, ‘chen‘), (‘age‘, 24), (‘sex‘, ‘male‘)]>>> v = [‘chen‘, 24]>>> zip(t,v)[(‘name‘, ‘chen‘), (‘age‘, 24)]
  • 也可能會使用列表來儲存資料,但是這樣不夠直觀,因為訪問的時候都是用下標來進行訪問。由此,就產生了字典{}這種資料結構

    字典是python種唯一的映射類型(雜湊表)
    字典的對象是可變的,但是字典的鍵必須使用不可變的對象,並且一個字典中可以使用不同類型的索引值。
    keys() 或者values()返回鍵列表或者值列表。
    items()返回包含索引值對的元組

建立字典方法一:{}
>>> dic = {0:0,1:1,2:2}>>> dic[0]0>>> dic[2]2>>> dic = {0:‘00‘,1:‘11‘,2:‘22‘}>>> dic[0]‘00‘>>> dic = {0:‘123‘,name:‘chenwen‘,‘x‘:456}Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name ‘name‘ is not defined>>> name = None>>> dic = {0:‘123‘,name:‘chenwen‘,‘x‘:456}>>> name>>> dic{0: ‘123‘, ‘x‘: 456, None: ‘chenwen‘}
  • 注意
    上面代碼中的,出錯資訊,意思是,name還沒定義,所以之後將name定義之後,才可以順利建立字典。建立之後,其實是以name的值做鍵。
    並不是建立字典的時候直接定義name的值。
>>> a = 1>>> b = 2>>> dic = {a:‘aaa‘,‘b‘:‘bbb‘}>>> a1>>> b2>>> dic{1: ‘aaa‘, ‘b‘: ‘bbb‘}
方法二: 使用Factory 方法dict()
>>> dict(one=1, two=2){‘two‘: 2, ‘one‘: 1}>>> dict({‘one‘: 1, ‘two‘: 2}){‘two‘: 2, ‘one‘: 1}>>> dict(zip((‘one‘, ‘two‘), (1, 2))){‘two‘: 2, ‘one‘: 1}>>> dict([[‘two‘, 2], [‘one‘, 1]]){‘two‘: 2, ‘one‘: 1}
方法三: 內建方法:fromkeys()
  • 字典中的元素具有相同的值,預設為None
>>> {}.fromkeys((‘x‘,‘y‘)){‘y‘: None, ‘x‘: None}>>> {}.fromkeys((‘x‘,‘y‘),-1){‘y‘: -1, ‘x‘: -1}
訪問字典中的值
>>> dic = {0:‘123‘,name:‘chenwen‘,‘x‘:456}>>> for k in dic:...     print k...0xNone>>> for k in dic:...     print dic[k]...123456chenwen
更新和刪除
>>> dic = {0:‘123‘,name:‘chenwen‘,‘x‘:456}>>> dic[‘like‘] = "DOTA">>> dic{0: ‘123‘, ‘x‘: 456, ‘like‘: ‘DOTA‘, None: ‘chenwen‘}>>> dic[‘like‘] = "GIRL">>> dic{0: ‘123‘, ‘x‘: 456, ‘like‘: ‘GIRL‘, None: ‘chenwen‘}>>> del(dic[None])>>> dic{0: ‘123‘, ‘x‘: 456, ‘like‘: ‘GIRL‘}>>> dic.pop(0)‘123‘>>> dic{‘x‘: 456, ‘like‘: ‘GIRL‘}>>> dic.clear()>>> dic{}>>> dic = {0:‘123‘,name:‘chenwen‘,‘x‘:456}>>> del(dic)>>> dicTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name ‘dic‘ is not defined>>> #注意:clear 和del 是不同的,clear只是清空,但是del則是... #將整個變數刪除,相當於沒定義

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.