Python入門(七) dict

來源:互聯網
上載者:User

標籤:

    Python中的dict也稱作關聯陣列或者是雜湊表,由鍵與值成對組成。

    1. dict的建立:用{}括起來,鍵與值之間用:分割,每一個索引值對之間用,分割

dict1 = {‘name‘:‘billy‘, ‘age‘:28}print(dict1)>>> {‘age‘: 28, ‘name‘: ‘billy‘}

    注意: 鍵必須獨一無二,而且必須是不可變,如字串、數字與tuple。

            值可以取任意類型,可以隨意修改。

    2. 訪問dict中的元素:通過鍵來訪問

print(dict1[‘name‘]>>> billyprint(dict1[‘age‘])>>> 28

    但是如果訪問的鍵不存在,則會引發異常

print(dict1[‘sex‘])Traceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    print(dict1[‘sex‘])KeyError: ‘sex‘

    要避免這個問題,我們可以用get方法來判斷

value = dict1.get(‘sex‘) #此時value = Noneif value:    print(‘the value of sex exist‘)else:    print(‘the value of sex does not exist‘)>>> the value of sex does not exist

    遍曆整個dict

#method 1for k in dict1:    print(k, dict1[k])>>>age 28name billy#method 2for (k,v) in dict1.items():    print(k, v)>>> age 28name billy#method 3for k in dict1.keys():    print(k, dict1[k])>>>age 28name billy

    3. 增加/刪除元素

#增加元素dict1[‘sex‘] = ‘male‘print(dict1)>>> {‘sex‘: ‘male‘, ‘age‘: 28, ‘name‘: ‘billy‘}#刪除元素del dict1[‘sex‘]print(dict1)>>> {‘age‘: 28, ‘name‘: ‘billy‘}#如果要刪除元素的鍵不存在,則引發異常del dict1[‘sex‘]Traceback (most recent call last):  File "<pyshell#42>", line 1, in <module>    del dict1[‘sex‘]KeyError: ‘sex‘#這個時候可以用到上面提到的get方法來判斷鍵是否存在,如果存在再執行刪除操作!

    修改元素的值

dict1[‘age‘] = 25print(dict1)>>> {‘age‘: 25, ‘name‘: ‘billy‘}

    4. dict其他常用方法:

1)copy() : 複製dict中的所有元素

dict2 = dict1.copy()print(dict2)>>> {‘name‘: ‘billy‘, ‘age‘: 25}

2)clear() : 清空dict中的所有元素

dict2.clear()print(dict2)>>> {}

3) keys() : 以列表方式返回dict中的所有鍵

for k in dict1.keys():    print(k)>>> agename

4) values() : 以列表方式返回dict中的所有值

for v in dict1.values():    print(v)>>> 25billy

5) len() : 擷取dict中元素的個數

print(len(dict1))>>> 2

dict在實際的開發中是非常有用的,比如我們在編寫http的服務程式時,可以把http的要求標頭中的每個欄位儲存在dict中,使用起來也非常方便。

Python入門(七) dict

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.