python基礎系列——字典知識點,函數及操作(持續更新中)

前言:

此文爲本人在學習python過程中,整理出來的學習筆記。主要參考書目有:
1、《python編程:從入門到實踐》;
2、《python學習手冊》;
3、《像計算機科學家一樣思考Python》

一 字典簡介

字典可以當做是無序的集合,字典與列表最主要的差別在於:字典中的元素(也可叫值,value)是通過鍵(key)來存取的,而不是通過偏移存取。
字典的主要屬性如下:

  1. 通過鍵而不是偏移量來讀取
  2. 任意對象的無序集合
  3. 可變長、異構、任意嵌套
  4. 屬於可變映射類型
  5. 對象引用表

字典常用操作表

在這裏插入圖片描述

二 字典的基本操作

2.1 字典的創建

字典可通過花括號{},中間加上’key’ : ‘value’,的方式直接創建,如:

#爲了代碼的美觀可用此種方式書寫。
info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}
print(info)
#運行結果:{'name': 'Tom', 'age': 18, 'job': ['designer', 'cook']}

字典的鍵可以是:數字、字符串,但不可是列表等容器
字典的值可以是任意對象,如:數字,字符串,列表,字典等

2.1.1 遍歷的方式創建字典

也可以通過對兩個相同長度的列表進行遍歷,並分別賦值給鍵和值,來創建一個字典,如:

ageinfo = {}
names = ['小明','小李','小周','小二']
foods = ['18','20','26','24']

for num in range(0,len(names)):
	ageinfo[names[num]] = foods[num]

print(ageinfo)
#運行結果:{'小明': '18', '小李': '20', '小周': '26', '小二': '24'}

上述代碼可用一個更簡單的方式來創建
利用zip函數:

names = ['小明','小李','小周','小二']
ages = ['18','20','26','24']

ageinfo = dict(zip(names,ages))  #zip函數從兩個列表中分別取一項!
print(ageinfo)
#運行結果:{'小明': '18', '小李': '20', '小周': '26', '小二': '24'}

2.1.2 其他幾種字典的創建方法

ageinfo = dict([('name','小明'),('age',26)])
print(ageinfo)
#運行結果:{'name': '小明', 'age': 26}

另外一種方法:


ageinfo = dict(name = '小明',age = 26)
print(ageinfo)
#運行結果:{'name': '小明', 'age': 26}

2.2 字典值的修改

字典和列表一樣,也屬於可變序列,可直接修改:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info['age'] = 22
print(info)
#運行結果:{'name': 'Tom', 'age': 22, 'job': ['designer', 'cook']}

2.3 len等內置函數

len函數也可作用於字典,獲取的是字典中鍵的個數。

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(len(info))
#運行結果:3

in 方法:in方法默認查找被查找元素是否在字典鍵中(keys()方法爲提取字典中的鍵),返回一個布爾值。

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print('name' in info)
#運行結果:True
print('age' in info.keys())
#運行結果:True

in也可用來尋找字典值中的元素:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(18 in info.values())
#運行結果:True

#但是注意!!!
print('cook' in info.values())
#運行結果:False 

三 字典方法調用

3.1 keys,values方法

keys和values方法可直接獲得一個類似列表的對象:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.keys())
#運行結果:dict_keys(['name', 'age', 'job'])
print(info.values())
#運行結果:dict_values(['Tom', 18, ['designer', 'cook']])

也可用list函數來創建一個真實的列表:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

keys_list = list(info.keys())
print(keys_list)
#運行結果:['name', 'age', 'job']

3.2 items方法

items方法可同時輸出字典的鍵和值:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.items())
#運行結果:dict_items([('name', 'Tom'), ('age', 18), ('job', ['designer', 'cook'])])

3.2.1 字典的遍歷

字典鍵的遍歷:

#接上字典代碼
for key in info.keys():
	print(key)
'''
運行結果:
name
age
job '''

字典值得遍歷:

for value in info.values():
	print(value)
'''運行結果爲:
Tom
18
['designer', 'cook']
'''

字典值與鍵的遍歷:

for key , value in info.items():
	print(key,value)
'''
運行結果:
name Tom
age 18
job ['designer', 'cook']
'''

3.3 pop與del方法

與列表類似,字典也可通過pop,del方法來刪除其內部元素:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info.pop('name')
print(info)
#運行結果:{'age': 18, 'job': ['designer', 'cook']}

del 用法

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

del info['age']
print(info)
#運行結果:{'name': 'Tom', 'job': ['designer', 'cook']}

3.4 update方法

字典的update方法有點類似於合併:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info_2 = {'add' : '北京'}

info.update(info_2)
print(info)
#運行結果:{'name': 'Tom', 'age': 18, 'job': ['designer', 'cook'], 'add': '北京'}

update會覆蓋兩個字典中重複的鍵的值:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info_2 = {
	'add' : '北京',
	'age' : 25
}

info.update(info_2)
print(info)
#運行結果:{'name': 'Tom', 'age': 25, 'job': ['designer', 'cook'], 'add': '北京'}

3.5 get方法

get方法用的比較少,可以獲得鍵對應的值。但其特殊地方在於,當需獲取的鍵在字典中不存在時,返回None,而不會報錯。如:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.get('name'))
#運行結果:Tom
print(info.get('add'))
#運行結果:None
print(info.get('add','beijing'))
#運行結果:beijing

3.6 fromkeys方法

formkeys也是一種創建字典的方法,用這個方法可創建一個具有相同值得初始化的一個列表:

ageinfo = dict.fromkeys(['小明','小李','小周','小二'],0)
print(ageinfo)
運行結果:{'小明': 0, '小李': 0, '小周': 0, '小二': 0}

其也可對一個已存在的字典進行初始化操作:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

initinfo = info.fromkeys(info.keys(),0)
print(initinfo)
#運行結果:{'name': 0, 'age': 0, 'job': 0}

也可以用字符串來快速創建一個具有初始化值得字典:

infodict = dict.fromkeys('abcdefg') #不傳入值參數,則默認爲None
print(infodict)
#運行結果:{'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'g': None}

3.7 字典解析

字典解析與列表解析一樣,後期將會安排專門章節進行介紹。

d = {number : number**2 for number in [1,2,3,4]}
print(d)
#運行結果:{1: 1, 2: 4, 3: 9, 4: 16}

3.8 有序的打印字典的值

因字典是無序的組合,所以在需要按特定順序的輸出字典中的值有一定麻煩,可採用以下方法:

info = {'2':'b','1':'a','5':'e','3':'c','4':'d'}
#直接遍歷得到的爲無序的值:
for key in info:
	print(info[key],end = '-')
#運行結果爲:b-a-e-c-d-

for key in sorted(info):
	print(info[key,end = '-'])
#運行結果:a-b-c-d-e-

結束語:

以上爲本人根據所閱讀書籍、博客、視頻學習後,所整理出的內容。
因學習時間有限,有不足及錯誤地方,歡迎大家指出。
整理不易,歡迎點贊,收藏,轉載(請註明出處,如需轉到其他平臺請私信!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章