1. 程式人生 > 其它 >python學習筆記(初極)—3.資料序列(字典、集合)

python學習筆記(初極)—3.資料序列(字典、集合)

這部分介紹字典和集合的相關內容

3.4字典

  字典⾥⾯的資料是以鍵值對(key-value)形式出現,字典資料和資料順序沒有關係,即字典不⽀持下標,需要按照對應的鍵的名字查詢資料。字典為可變型別

  建立字典語法:符號為⼤括號

         資料為鍵值對形式出現

         各個鍵值對之間⽤逗號隔開

# 有資料字典
dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}

# 空字典
dict2 = {}
dict3 = dict()

3.4.1字典的常見操作

  增、刪、改、查

  語法:字典序列[key] = 值

  注意:如果key存在則修改這個key對應的value值;如果key不存在則新增此鍵值對

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}

dict1['name'] = 'Rose'
# 結果:{'name': 'Rose', 'age': 20, 'gender': '男'}
print(dict1)

dict1['id'] = 110
# {'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}
print(dict1)

  del() / del:刪除字典或刪除字典中指定鍵值對

dict1 = {'name': 'Tom', 'age': 20, 'gender': '
'} del dict1['gender'] # 結果:{'name': 'Tom', 'age': 20} print(dict1)

  clear():清空字典

  語法(與增加操作一樣):字典序列[key] = 值

  此時key在原字典中存在

  key值查詢,查詢的key存在,則返回對應的值;否則報錯

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
print(dict1['name']) # Tom
print(dict1['id']) # 報錯

  get()方法查詢:字典序列.get(key, 預設值)

  注意:

如果查詢的key不存在則返回第⼆個引數(預設值),如果省略第⼆個引數,則返回 None

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
print(dict1.get('name')) # Tom
print(dict1.get('id', 110)) # 110
print(dict1.get('id')) # None

  key()方法

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])

  values()方法

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
print(dict1.values()) # dict_values(['Tom', 20, '男'])

  items()方法,返回鍵值對迭代器,內部資料是元組型別

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
print(dict1.items()) # dict_items([('name', 'Tom'), ('age', 20), ('gender','男')])

3.4.2字典的迴圈遍歷

  遍歷key

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
for key in dict1.keys():
    print(key)

  遍歷value(與上面程式碼類似)

  遍歷鍵值對

dict1 = {'name': 'Tom', 'age': 20, 'gender': ''}
for item in dict1.items():
    print(item)
for key, value in dict1.items():
    print(f'{key} = {value}')

 

3.5集合

  集合可以去掉重複資料;集合資料是⽆序的,故不⽀持下標

  建立集合可以使⽤ {} 或 set() , 但是如果要建立空集合只能使⽤ set() ,因為 {} ⽤來建立空字典

s1 = {10, 20, 30, 40, 50}
s2 = {10, 30, 20, 10, 30, 40, 30, 50}
s3 = set('abcdefg')

s4 = set()
print(type(s4)) # set

s5 = {}
print(type(s5)) # dict

3.5.1集合常見的操作方法

  add(),因為集合有去重功能,所以,當向集合內追加的資料是當前集合已有資料的話,則不進⾏任何操作

s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1) # {100, 10, 20}

  update(), 追加的資料是序列

s1 = {10, 20}
# s1.update(100) # 報錯
s1.update([100, 200])
s1.update('abc')
print(s1)  # abc分別加進去

  remove(),刪除集合中的指定資料,如果資料不存在則報錯

s1 = {10, 20}
s1.remove(10)
print(s1)

  discard(),刪除集合中的指定資料,如果資料不存在也不會報錯

  in:判斷資料在集合序列

  not in:判斷資料不在集合序列

s1 = {10, 20, 30, 40, 50}
print(10 in s1)
print(10 not in s1)