網站首頁 編程語言 正文
1.字典的概念
字典和列表類似,也是可變序列,不過和列表不同,它是無序的可變序列,保存的內容是以鍵值對(key:value)形式存放的 字典的每個鍵值之間用冒號:分隔,每個鍵值對之間用,隔開,整個字典包含在{ }中
dict = {key1:value1,key2:value2}
2.字典的主要特征
1:通過鍵而不是通過索引來讀取
2:字典是任意對象的無序集合
3:字典是可變的,可以隨意嵌套
4:字典的鍵必須唯一
5:字典的鍵必須不可變
3.創建字典的三種方法
# 第一種方法 dic1 = {'name':'hacker','age':'18'} # 第二種方法 dic2 = dict(name='hacker',age='18') # 第三種方法 dic3 = dict([('name','hacker'),('age','18')])
4.字典常用方法
1.clear()
定義 clear()方法清空字典中的所有元素(返回空字典) ??舉個栗子??清空car字典中的所有元素
car = {"brand": "Porsche", "model": "911", "year": 1963} car.clear() print(car)
運行結果如下:
{}
2.copy()
定義 copy()方法返回字典的副本(復制字典) ??舉個栗子??復制car字典
car = {"brand": "Porsche", "model": "911", "year": 1963} res = car.copy() print(res)
運行結果如下
{'brand': 'Porsche', 'model': '911', 'year': 1963}
3.get()
定義 get()方法返回指定鍵的值 ??舉個栗子??使用get方法返回"model"的值
car = {"brand": "Porsche", "model": "911", "year": 1963} x = car.get("model") print(x)
運行結果如下:
911
4.keys()
定義返回字典里的所有鍵 ??舉個栗子??返回car字典的所有鍵
car = {"brand": "Porsche", "model": "911", "year": 1963} res = car.keys() print(res)
運行結果如下:
dict_keys(['brand', 'model', 'year'])
5.values()
定義 返回字典的所有值 ??舉個栗子??返回car字典的所有值
car = {"brand": "Porsche", "model": "911", "year": 1963} res = car.values() print(res)
運行結果如下:
dict_values(['Porsche', '911', 1963])
6.items()
定義返回字典的所有鍵值對 ??舉個栗子??返回car字典的所有鍵值對
car = {"brand": "Porsche", "model": "911", "year": 1963} res = car.items() print(res)
運行結果如下:
dict_items([('brand', 'Porsche'), ('model', '911'), ('year', 1963)])
7.del()
定義 刪除字典元素 ??舉個栗子??刪除car字典的"model"的鍵
car = {"brand": "Porsche", "model": "911", "year": 1963} del car["model"] print(car)
運行結果如下:
{'brand': 'Porsche', 'year': 1963}
8.zip()
定義 zip()方法將鍵值打包成一個字典
li1 = ["name","age"] li2 = ["hacker","18"] print(dict(zip(li1,li2)))
運行結果如下:
{'name': 'hacker', 'age': '18'}
以上就是字典常用的方法整理
原文鏈接:https://blog.csdn.net/xqe777/article/details/123212001
相關推薦
- 2022-03-11 解決 fatal error LNK1120: 1 unresolved externals 問題
- 2022-10-31 Python遍歷列表時刪除元素案例_python
- 2022-04-17 合并兩個遞增有序的單鏈表,使合并后仍遞增有序
- 2022-08-22 Git遠程刪除某個歷史提交記錄方法詳解_相關技巧
- 2023-03-22 WinPC搭建nginx服務器的實現步驟_nginx
- 2023-11-12 python enumerate函數用法
- 2023-07-09 關于 axios 是什么?以及怎么用?
- 2022-05-13 error hawk@0.10.2: The engine “node“ is incompatib
- 最近更新
-
- 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同步修改后的遠程分支