python字典的基本操作
时间: 2023-11-05 11:02:14 浏览: 63
1. 创建字典
可以使用{}或dict()创建一个空字典,也可以在{}中使用键值对来初始化一个字典。
```python
d = {} # 空字典
d = dict() # 空字典
d = {'a': 1, 'b': 2} # 初始化字典
```
2. 访问字典中的值
可以使用键来访问字典中的值。
```python
d = {'a': 1, 'b': 2}
print(d['a']) # 1
print(d.get('b')) # 2
```
如果键不存在,使用[]访问字典中的值会抛出KeyError异常,而使用get()方法则会返回None。
3. 更新字典
可以通过键来更新字典中的值,如果键不存在,则会新增一个键值对。
```python
d = {'a': 1, 'b': 2}
d['a'] = 3 # 更新键'a'对应的值为3
d['c'] = 4 # 新增键'c'和它对应的值4
print(d) # {'a': 3, 'b': 2, 'c': 4}
```
4. 删除键值对
可以使用del语句或pop()方法来删除字典中的键值对。
```python
d = {'a': 1, 'b': 2}
del d['a'] # 删除键'a'对应的键值对
d.pop('b') # 删除键'b'对应的键值对
print(d) # {}
```
5. 遍历字典
可以使用for循环遍历字典中的键值对。
```python
d = {'a': 1, 'b': 2}
for key in d:
print(key, d[key])
```
也可以使用items()方法来遍历字典中的键值对。
```python
d = {'a': 1, 'b': 2}
for key, value in d.items():
print(key, value)
```
6. 其他常用方法
- keys():返回字典中所有的键
- values():返回字典中所有的值
- len():返回字典中键值对的数量
```python
d = {'a': 1, 'b': 2}
print(d.keys()) # dict_keys(['a', 'b'])
print(d.values()) # dict_values([1, 2])
print(len(d)) # 2
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)