python字典增加元素
时间: 2023-09-06 21:12:41 浏览: 42
可以使用以下方法向Python字典中增加元素:
1. 直接使用键值对添加元素
```python
my_dict = {'name': 'John', 'age': 25}
my_dict['gender'] = 'male'
print(my_dict)
# 输出:{'name': 'John', 'age': 25, 'gender': 'male'}
```
2. 使用`update()`方法添加元素
```python
my_dict = {'name': 'John', 'age': 25}
my_dict.update({'gender': 'male', 'address': '123 Main St'})
print(my_dict)
# 输出:{'name': 'John', 'age': 25, 'gender': 'male', 'address': '123 Main St'}
```
3. 使用`setdefault()`方法添加元素
```python
my_dict = {'name': 'John', 'age': 25}
my_dict.setdefault('gender', 'male')
my_dict.setdefault('address', '123 Main St')
print(my_dict)
# 输出:{'name': 'John', 'age': 25, 'gender': 'male', 'address': '123 Main St'}
```
注意:如果使用`setdefault()`方法添加元素,如果指定的键已经存在,则不会更新该键对应的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)