python 循环dict的key ,value
时间: 2023-11-30 20:25:28 浏览: 106
python迭代dict的key和value的方法
可以使用字典的items()方法来获取字典中所有的键值对,然后使用for循环遍历即可,示例代码如下:
```python
my_dict = {"name": "Alice", "age": 20, "gender": "female"}
# 遍历字典中所有的键值对
for key, value in my_dict.items():
print(key, value)
```
输出结果为:
```
name Alice
age 20
gender female
```
如果只想循环字典的key,可以使用keys()方法获取所有的key,示例代码如下:
```python
my_dict = {"name": "Alice", "age": 20, "gender": "female"}
# 遍历字典中所有的key
for key in my_dict.keys():
print(key)
```
输出结果为:
```
name
age
gender
```
如果只想循环字典的value,可以使用values()方法获取所有的value,示例代码如下:
```python
my_dict = {"name": "Alice", "age": 20, "gender": "female"}
# 遍历字典中所有的value
for value in my_dict.values():
print(value)
```
输出结果为:
```
Alice
20
female
```
阅读全文