newechoes/src/content/理解计算机/python/字典.md
2025-04-19 01:06:52 +08:00

55 lines
962 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 字典
date: 2024-06-06T23:51:30Z
tags: []
---
## 创建方式
### 第一种使用{}直接创建字典
`d={key1:value1,key2:value2....}`
语法结构如下:
`dict(key1=value1,key2=value2....)`
### 第二种使用内置函数dict()创建字典
#### 1)映射函数
`zip(lst1,lst2)`
lst1为键
lst2为值
##### 字典转列表
`列表名=zdict(字典名)`
## 字典元素的取值
d[key]或d.get(key)
## 字典元素的遍历
### 1)遍历出key与value的元组
`for element in d.items(): pass`
### 2)分别遍历出key与value
`for key,value in d.items(): pass`
## 相关的操作方法
获取所有的key数据
`d.keys()`
获取所有的value的数据
`d.values()`
key存在获取相应的value,同时删除key-value对,否则获取默认值
`d.pop(key,default)`
随机从字典种取出一个key-value对结果为元组类型,同时将该key-value从字典种删除
`d.popitem()`
清空字典中所有的key-value对
`d.clear()`