網站首頁 編程語言 正文
大家好,本期給大家帶來Python字典11個方法的全面解析,希望對你有所幫助。
字典(Dictionary)是Python提供的一種常用的數據結構,它用于存放具有映射關系的數據,由鍵(key)和值(value)成對組成,鍵和值中間以冒號:隔開,項之間用逗號隔開,整個字典由大括號{}括起來,格式如下:
dic = {key1 : value1, key2 : value2 }
字典也被稱作關聯數組或哈希表,下面是幾種常見的字典創建方式:
# 方法1 dic1 = { 'Author' : 'Python' , 'age' : 99 , 'sex' : '男' } # 方法2 lst = [('Author', 'Python'), ('age', 99), ('sex', '男')] dic2 = dict(lst) # 方法3 dic3 = dict( Author = 'Python', age = 99, sex = '男') # 方法4 list1 = ['Author', 'age', 'sex'] list2 = ['Python', 99, '男'] dic4 = dict(zip(list1, list2))
字典創建的方式還有很多種,這里不再贅述。
字典由 dict 類代表,可以使用 dir(dict) 來查看該類包含哪些方法,輸入命令,可以看到如下輸出結果:
print('methods = ',methods) methods = ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
字典的方法和屬性有很多種,這里我們重點介紹以下11種方法:
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
1.dict.clear()
clear() 用于清空字典中所有元素(鍵-值對),對一個字典執行 clear() 方法之后,該字典就會變成一個空字典:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', 99, '男'] dic1 = dict(zip(list1, list2)) # dic1 = {'Author': 'Python', 'age': 99, 'sex': '男'} dic1.clear() # dic1 = {}
2.dict.copy()
copy() 用于返回一個字典的淺拷貝:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', 99, '男'] dic1 = dict(zip(list1, list2)) dic2 = dic1 # 淺拷貝: 引用對象 dic3 = dic1.copy() # 淺拷貝:深拷貝父對象(一級目錄),子對象(二級目錄)不拷貝,還是引用 dic1['age'] = 18 # dic1 = {'Author': 'Python', 'age': 18, 'sex': '男'} # dic2 = {'Author': 'Python', 'age': 18, 'sex': '男'} # dic3 = {'Author': 'Python', 'age': 99, 'sex': '男'}
其中 dic2 是 dic1 的引用,所以輸出結果是一致的,dic3 父對象進行了深拷貝,不會隨dic1 修改而修改,子對象是淺拷貝所以隨 dic1 的修改而修改,注意父子關系。
拓展深拷貝:copy.deepcopy()
import copy list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) dic2 = dic1 dic3 = dic1.copy() dic4 = copy.deepcopy(dic1) dic1['age'].remove(18) dic1['age'] = 20 # dic1 = {'Author': 'Python', 'age': 20, 'sex': '男'} # dic2 = {'Author': 'Python', 'age': 20, 'sex': '男'} # dic3 = {'Author': 'Python', 'age': [99], 'sex': '男'} # dic4 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'}
dic2 是 dic1 的引用,所以輸出結果是一致的;dic3 父對象進行了深拷貝,不會隨dic1 修改而修改,子對象是淺拷貝所以隨 dic1 的修改而修改;dic4 進行了深拷貝,遞歸拷貝所有數據,相當于完全在另外內存中新建原字典,所以修改dic1不會影響dic4的數據
3.dict.fromkeys()
fromkeys() 使用給定的多個鍵創建一個新字典,值默認都是 None,也可以傳入一個參數作為默認的值:
list1 = ['Author', 'age', 'sex'] dic1 = dict.fromkeys(list1) dic2 = dict.fromkeys(list1, 'Python') # dic1 = {'Author': None, 'age': None, 'sex': None} # dic2 = {'Author': 'Python', 'age': 'Python', 'sex': 'Python'}
4.dict.get()
get() 用于返回指定鍵的值,也就是根據鍵來獲取值,在鍵不存在的情況下,返回 None,也可以指定返回值:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) Author = dic1.get('Author') # Author = Python phone = dic1.get('phone') # phone = None phone = dic1.get('phone','12345678') # phone = 12345678
5.dict.items()
items() 獲取字典中的所有鍵-值對,一般情況下可以將結果轉化為列表再進行后續處理:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) items = dic1.items() print('items = ', items) print(type(items)) print('items = ', list(items)) # items = dict_items([('Author', 'Python'), ('age', [18, 99]), ('sex', '男')]) # <class 'dict_items'> # items = [('Author', 'Python'), ('age', [18, 99]), ('sex', '男')]
6.dict.keys()
keys() 返回一個字典所有的鍵:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) keys = dic1.keys() print('keys = ', keys) print(type(keys)) print('keys = ', list(keys)) # keys = dict_keys(['Author', 'age', 'sex']) # <class 'dict_keys'> # keys = ['Author', 'age', 'sex']
7.dict.pop()
pop() 返回指定鍵對應的值,并在原字典中刪除這個鍵-值對:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) sex = dic1.pop('sex') print('sex = ', sex) print('dic1 = ',dic1) # sex = 男 # dic1 = {'Author': 'Python', 'age': [18, 99]}
8.dict.popitem()
popitem() 刪除字典中的最后一對鍵和值:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) dic1.popitem() print('dic1 = ',dic1) # dic1 = {'Author': 'Python', 'age': [18, 99]}
9.dict.setdefault()
setdefault() 和 get() 類似, 但如果鍵不存在于字典中,將會添加鍵并將值設為default:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) dic1.setdefault('Author', '') print('dic1 = ',dic1) # dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'} dic1.setdefault('name', '') print('dic1 = ',dic1) # dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男', 'name': ''}
10.dict.update(dict1)
update() 字典更新,將字典dict1的鍵-值對更新到dict里,如果被更新的字典中己包含對應的鍵-值對,那么原鍵-值對會被覆蓋,如果被更新的字典中不包含對應的鍵-值對,則添加該鍵-值對:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) print('dic1 = ',dic1) # dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'} list3 = ['Author', 'phone' ] list4 = ['', 12345678] dic2 = dict(zip(list3, list4)) print('dic2 = ',dic2) # dic2 = {'Author': '', 'phone': 12345678} dic1.update(dic2) print('dic1 = ',dic1) # dic1 = {'Author': '', 'age': [18, 99], 'sex': '男', 'phone': 12345678}
11.dict.values()
values() 返回一個字典所有的值:
list1 = ['Author', 'age', 'sex'] list2 = ['Python', [18,99], '男'] dic1 = dict(zip(list1, list2)) values = dic1.values() print('values = ', values) print(type(values)) print('values = ', list(values)) # values = dict_values(['Python', [18, 99], '男']) # <class 'dict_values'> # values = ['Python', [18, 99], '男']
原文鏈接:https://blog.csdn.net/weixin_38037405/article/details/122726343
相關推薦
- 2022-10-16 python中列表添加元素的幾種方式(+、append()、extend())_python
- 2022-02-18 spring常見錯誤:Error creating bean with name ‘xxx‘
- 2022-12-06 c++入門必學算法之快速冪思想及實現_C 語言
- 2022-09-24 教你創建一個帶診斷工具的.NET鏡像_C#教程
- 2022-03-31 C語言值傳遞和地址傳遞詳解_C 語言
- 2022-08-23 Python可視化模塊altair的使用詳解_python
- 2022-04-08 WPF中Style樣式及其觸發器_基礎應用
- 2022-01-16 ES6新增聲明格式、變量解構賦值及模板字符串
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支