python dict循环
时间: 2023-09-12 07:05:48 浏览: 101
Python for循环及基础用法详解
在Python中,你可以使用`for`循环来遍历字典(dict)的键(keys)、值(values)或者键值对(items)。这里有几种常见的方法:
1. 遍历键:
```python
my_dict = {"name": "John", "age": 25, "city": "New York"}
for key in my_dict:
print(key)
```
输出:
```
name
age
city
```
2. 遍历值:
```python
my_dict = {"name": "John", "age": 25, "city": "New York"}
for value in my_dict.values():
print(value)
```
输出:
```
John
25
New York
```
3. 遍历键值对:
```python
my_dict = {"name": "John", "age": 25, "city": "New York"}
for key, value in my_dict.items():
print(key, value)
```
输出:
```
name John
age 25
city New York
```
希望这些示例对你有帮助!
阅读全文