盤點 Python 基礎之字典的那些事兒

一、前言

如果有列表 ,需要對 "xiaoWang" 這個名字進行修改,則要通過對應的索引值進行代碼修改。

 nameList = ['xiaoZhang', 'xiaoWang', 'xiaoLi']
 nameList[1] = 'xiaoxiaoWang

如果列表的順序發生了變化,如下:

 nameList = ['xiaoWang', 'xiaoZhang',  'xiaoLi'];

此時就需要修改下標,才能完成名字的修改。

 nameList[0] = 'xiaoxiaoWang'

有沒有方法,既能存儲多個數據,還能在訪問元素的很方便就能夠定位到需要的那個元素呢?這就是字典。

二、字典的介紹

  info = {'name':'班長', 'id':100, 'sex':'f', 'address':'地球亞洲中國北京'}
    print(info['name'])
    print(info['address'])

運行結果:

若訪問不存在的鍵,則會報錯:

>>> info['age']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'age'

在我們不確定字典中是否存在某個鍵而又想獲取其值時,可以使用 get 方法,還可以設置默認值。

>>> age = info.get('age')
>>> age    #'age'鍵不存在,所以age爲None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # 若info中不存在'age'這個鍵,就返回默認值18
>>> print(age) 
18  #運行結果

1. 字典的常見操作 1

<1> 添加元素

   info = {'name':'班長', 'sex':'f', 'address':'地球亞洲中國北京'}
    print('id爲:%d'%info['id'])

運行結果:

如果在使用 變量名 ['鍵'] = 數據 時,這個 “鍵” 在字典中,不存在,那麼就會新增這個元素。

添加新的元素。

   info = {'name':'班長', 'sex':'f', 'address':'地球亞洲中國北京'}
    # print('id爲:%d'%info['id'])#程序會終端運行,因爲訪問了不存在的鍵
    newId = input('請輸入新的學號')
    info['id'] = newId
    print('添加之後的id爲:%d'%info['id'])

運行結果:

   請輸入新的學號188
   添加之後的id爲: 188

<2> 刪除元素

對字典進行刪除操作,有一下幾種:

del 刪除指定的元素

   info = {'name':'班長', 'sex':'f', 'address':'地球亞洲中國北京'}
    print('刪除前,%s'%info['name'])
    del info['name']
    print('刪除後,%s'%info['name'])

運行結果:

del 刪除整個字典。

   info = {'name':'monitor', 'sex':'f', 'address':'China'}
    print('刪除前,%s'%info)
    del info
    print('刪除後,%s'%info)

運行結果:

clear 清空整個字典。

   info = {'name':'monitor', 'sex':'f', 'address':'China'}
    print('清空前,%s'%info)
    info.clear()
    print('清空後,%s'%info)

運行結果:

<3> 修改元素

字典的每個元素中的數據是可以修改的,只要通過 key 找到,即可修改。

   info = {'name':'班長', 'id':100, 'sex':'f', 'address':'地球亞洲中國北京'}
    newId = input('請輸入新的學號')
    info['id'] = int(newId)
    print('修改之後的id爲%d:'%info['id'])

運行結果:

2. 字典的常見操作 2

<1>len()

測量字典中,鍵值對的個數。

dict={"name":'zahnsan','sex':'m'}
print(len(dict))

運行結果:

<2>keys

返回一個包含字典所有 KEY 的列表。

dict={"name":'zahnsan','sex':'m'}
print(dict.keys())

運行結果:

<3>values

返回一個包含字典所有 value 的列表。

dict={"name":'zahnsan','sex':'m'}
print(dict.values())

運行結果:

<4>items

返回一個包含所有(鍵,值)元祖的列表。

dict={"name":'zahnsan','sex':'m'}
print(dict.items())

運行結果:

三、遍歷


語法:通過 for ... in ...: 的語法結構,我們可以遍歷字符串、列表、元組、字典等數據結構。

注意 :Python 語法的縮進

先看一下字符串,列表和元組是怎麼遍歷的。

 字符串遍歷

>>> a_str = "hello itcast"
>>> for char in a_str:
...     print(char,end=' ')
...
h e l l o   i t c a s t #運行結果

 列表遍歷

>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
...     print(num,end=' ')
...
1 2 3 4 5 #運行結果

元組遍歷

>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
...     print(num,end=" ")
1 2 3 4 5 #運行結果

字典遍歷

1 . 遍歷字典的 key(鍵)

2 . 遍歷字典的 value(值)

3. 遍歷字典的項(元素)

4. 遍歷字典的 key-value(鍵值對)

5. enumerate()

chars = ['a', 'b', 'c', 'd']
for i, chr in enumerate(chars):
    print(i, chr)

運行結果:

四、總結


本文以生活中字典的實際應用,主要介紹了 Python 字典的基礎知識,用豐富的案例,幫助大家更好的去了解字典常見的的基礎操作。

使用 Python 編程語言,加深讀者對字典的認識,希望對大家的學習有幫助。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/HbdFiLzCUUEdWvOoaWhY3Q