1. 程式人生 > >python之字典操作

python之字典操作

遍歷字典 愛好 wim ems values n) 刪除 color 列表

字典操作代碼如下:

 1 #數據字典操作匯總
 2 person = {name: Mike, age: 25}
 3 print("初始的數據字典:", person)
 4 
 5 #訪問字典值
 6 print("獲取姓名:", person[name])
 7 
 8 #遍歷字典。註意字典不在乎順序,只關心對應關系。
 9 #還有keys()和values(),返回對應列表數據。
10 print("遍歷字典:")
11 for key, value in person.items():
12     print(key, value)
13 
14 #添加鍵值對
15
person[job] = singer 16 print("添加後的數據字典:", person) 17 18 #修改值 19 person[age] = 30 20 print("修改後的數據字典:", person) 21 22 #刪除鍵值對 23 del person[job] 24 print("刪除後的數據字典:", person) 25 26 #字典中嵌套列表及其遍歷 27 hobbys = {Mike: [singing, swim, reading], 28 Tom: [reading, dance]} 29
for key, values in hobbys.items(): 30 print(key + "的愛好是:") 31 for h in values: 32 print(h)

運行結果:

 1 初始的數據字典: {name: Mike, age: 25}
 2 獲取姓名: Mike
 3 遍歷字典:
 4 name Mike
 5 age 25
 6 添加後的數據字典: {name: Mike, age: 25, job: singer}
 7 修改後的數據字典: {name: Mike, age: 30, 
job: singer} 8 刪除後的數據字典: {name: Mike, age: 30} 9 Mike的愛好是: 10 singing 11 swim 12 reading 13 Tom的愛好是: 14 reading 15 dance

python之字典操作