標籤:ima val 多個 組成 new style put result 就是
字典介紹
想一想:
如果有列表
nameList = [‘xiaoZhang‘, ‘xiaoWang‘, ‘xiaoLi‘];
需要對"xiaoWang"這個名字寫錯了,通過代碼修改:
nameList[1] = ‘xiaoxiaoWang‘
如果列表的順序發生了變化,如下
nameList = [‘xiaoWang‘, ‘xiaoZhang‘, ‘xiaoLi‘];
此時就需要修改下標,才能完成名字的修改
nameList[0] = ‘xiaoxiaoWang‘
有沒有方法,既能儲存多個資料,還能在訪問元素的很方便就能夠定位到需要的那個元素呢?
答:
字典
另一個情境:
學生資訊列表,每個學生資訊包括學號、姓名、年齡等,如何從中找到某個學生的資訊?
>>> studens = [[1001, "王寶強", 24], [1002, "馬蓉", 23], [1005, "宋喆",24], ...]
迴圈遍曆? No!
<2>軟體開發中的字典
變數info為字典類型:
info = {‘name‘:‘班長‘, ‘id‘:100, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}
說明:
- 字典和列表一樣,也能夠儲存多個資料
- 列表中找某個元素時,是根據下標進行的
- 字典中找某個元素時,是根據‘名字‘(就是冒號:前面的那個值,例如上面代碼中的‘name‘、‘id‘、‘sex‘)
- 字典的每個元素由2部分組成,鍵:值。例如 ‘name‘:‘班長‘ ,‘name‘為鍵,‘班長‘為值
<3>根據鍵訪問值
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>>> age18
字典的常見操作<1>修改元素
字典的每個元素中的資料是可以修改的,只要通過key找到,即可修改
demo:
info = {‘name‘:‘班長‘, ‘id‘:100, ‘sex‘:‘f‘,‘address‘:‘地球亞洲中國北京‘}newId = input(‘請輸入新的學號‘)info[‘id‘] = int(newId)print(‘修改之後的id為%d:‘%info[‘id‘])
執行結果:
<2>添加元素
demo:
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}# print(‘id為:%d‘%info[‘id‘])#程式會終端運行,因為訪問了不存在的鍵newId = input(‘請輸入新的學號‘)info[‘id‘] = newIdprint(‘添加之後的id為:%s‘%info[‘id‘])
執行結果:
<3>刪除元素
對字典進行刪除操作,有一下幾種:
demo:del刪除指定的元素
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}print(‘刪除前,%s‘%info[‘name‘])del info[‘name‘]print(‘刪除後,%s‘%info[‘name‘])
執行結果:
demo:del刪除整個字典
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}print(‘刪除前,%s‘%info)del infoprint(‘刪除後,%s‘%info)
執行結果:
<4>len()
測量字典中,索引值對的個數
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}result=len(info)print(‘索引值對個數:,%d‘%result)
執行結果:
<5>keys
返回一個包含字典所有KEY的列表
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}result=info.keys()print(‘鍵,%s‘%result)
<6>values
返回一個包含字典所有value的列表
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}result=info.values()print(‘值,%s‘%result)
<7>items
返回一個包含所有(鍵,值)元祖的列表
info = {‘name‘:‘班長‘, ‘sex‘:‘f‘, ‘address‘:‘地球亞洲中國北京‘}result=info.items()print(‘%s‘%result)
python基礎-字典