免費做房產(chǎn)網(wǎng)站有哪些網(wǎng)絡(luò)推廣的公司更可靠
文章目錄
- 序言
- 1. 字典的創(chuàng)建和訪問
- 2. 字典如何添加元素
- 3. 字典作為函數(shù)參數(shù)
- 4. 字典排序
序言
- 總結(jié)字典的一些常見用法
1. 字典的創(chuàng)建和訪問
-
字典是一種可變?nèi)萜黝愋?#xff0c;可以存儲任意類型對象
-
key : value,其中value可以是任何數(shù)據(jù)類型,key必須是不可變的如字符串、數(shù)字、元組,不可以用列表
-
key是唯一的,如果出現(xiàn)兩次,后一個值會被記住
-
字典的創(chuàng)建
-
創(chuàng)建空字典
dictionary = {}
-
直接賦值創(chuàng)建字典
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175}
-
通過關(guān)鍵字dict和關(guān)鍵字參數(shù)創(chuàng)建字典
dictionary = dict(name='Nick', age=20, height=175)
dictionary = dict() for i in range(1, 5):dictionary[i] = i * i print(dictionary) # 輸出結(jié)果:{1: 1, 2: 4, 3: 9, 4: 16}
-
通過關(guān)鍵字dict和二元組列表創(chuàng)建
my_list = [('name', 'Nick'), ('age', 20), ('height', 175)] dictionary = dict(my_list)
-
通過關(guān)鍵字dict和zip創(chuàng)建
dictionary = dict(zip('abc', [1, 2, 3])) print(dictionary) # 輸出{'a': 1, 'b': 2, 'c': 3}
-
通過字典推導(dǎo)式創(chuàng)建
dictionary = {i: i ** 2 for i in range(1, 5)} print(dictionary) # 輸出{1: 1, 2: 4, 3: 9, 4: 16}
-
通過dict.fromkeys()來創(chuàng)建
dictionary = dict.fromkeys(range(5), 'x') print(dictionary) # 輸出{0: 'x', 1: 'x', 2: 'x', 3: 'x'}
這種方法用來初始化字典設(shè)置value的默認值
-
-
字典的訪問
-
通過鍵值對訪問
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175} print(dictionary['age'])
-
通過dict.get(key, default=None)訪問:default為可選項,指定key不存在時返回一個默認值,如果不設(shè)置默認返回None
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'} print(dictionary.get(3, '字典中不存在鍵為3的元素'))
-
遍歷字典的items
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'} print('遍歷輸出item:') for item in dictionary.items():print(item)print('\n遍歷輸出鍵值對:') for key, value in dictionary.items():print(key, ' : ', value)
-
遍歷字典的keys或values
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}print('遍歷keys:') for key in dictionary.keys():print(key)print('\n通過key來訪問:') for key in dictionary.keys():print(dictionary[key])print('\n遍歷value:') for value in dictionary.values():print(value)
-
遍歷嵌套字典
for key, value in dict_2.items():if type(value) is dict: # 通過if語句判斷value是不是字典for sub_key, sub_value in value.items():print(sub_key, "→", sub_value)
-
2. 字典如何添加元素
-
使用[]
dictionary = {} dictionary['name'] = 'Nick' dictionary['age'] = 20 dictionary['height'] = 175 print(dictionary)
-
使用update()方法
dictionary = {'name': 'Nick', 'age': 20, 'height': 175} dictionary.update({'age' : 22}) # 已存在,則覆蓋key所對應(yīng)的value dictionary.update({'2' : 'tetst'}) # 不存在,則添加新元素 print(dictionary)
3. 字典作為函數(shù)參數(shù)
-
字典作為參數(shù)傳遞時:函數(shù)內(nèi)對字典修改,原來的字典也會改變
dictionary = {'name': 'Nick', 'age': 20, 'height': 175} dictionary.update({'age': 22}) # 已存在,則覆蓋key所對應(yīng)的value dictionary.update({'2': 'test'}) # 不存在,則添加新元素 print(dictionary)def dict_fix(arg):arg['age'] = 24dict_fix(dictionary)print(dictionary) # age : 24
-
字典作為可變參數(shù)時:函數(shù)內(nèi)對字典修改,不會影響到原來的字典
dictionary = {'name': 'Nick', 'age': 20, 'height': 175} dictionary.update({'age': 22}) # 已存在,則覆蓋key所對應(yīng)的value dictionary.update({'2': 'test'}) # 不存在,則添加新元素 print(dictionary, '\n')def dict_fix(**arg):for key, value in arg.items():print(key, '->', value) # age : 22arg['age'] = 24dict_fix(**dictionary)print('\n', dictionary) # age : 22
-
關(guān)于字典作為**可變參數(shù)時的key類型說明
dictionary = {} dictionary.update({2: 'test'}) print(dictionary, '\n')def dict_fix(**arg):for key, value in arg.items():print(key, '->', value)arg['age'] = 24dict_fix(**dictionary)
- 報錯:TypeError: keywords must be strings,意思是作為**可變參數(shù)時,key必須是string類型
- 作為普通參數(shù)傳遞則不存在這個問題
dictionary = {} dictionary.update({2: 'test'}) print(dictionary, '\n')def dict_fix(arg):for key, value in arg.items():print(key, '->', value)arg['2'] = 'new'dict_fix(dictionary)
-
補充一個例子
def function(*a,**b):print(a)print(b) a=3 b=4 function(a, b, m=1, n=2) # (3, 4) {'n': 2, 'm': 1}
- 對于不使用關(guān)鍵字傳遞的變量,會被作為元組的一部分傳遞給*a,而使用關(guān)鍵字傳遞的變量作為字典的一部分傳遞給了**b
4. 字典排序
-
使用python內(nèi)置排序函數(shù)
sorted(iterable, key=None, reverse=False)
-
iterable:可迭代對象;key:用來比較的元素,取自迭代對象中;reverse:默認False升序, True降序
data = sorted(object.items(), key=lambda x: x[0]) # 使用x[0]的數(shù)據(jù)進行排序
【參考文章】
字典的創(chuàng)建方式
字典的訪問1
字典的訪問2
字典中添加元素
字典作為函數(shù)參數(shù)1
字典通過關(guān)鍵字參數(shù)傳參
字典作為可變參數(shù)時的key取值問題
*參數(shù)和** 形參的區(qū)別
created by shuaixio, 2023.10.05