python 遍历dict
时间: 2024-02-09 14:06:17 浏览: 68
在Python中,遍历字典(dict)有多种方式。以下是几种常见的遍历字典的方法:
1. 使用for循环遍历键(keys):
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
for key in my_dict:
print(key)
```
输出:
```
name
age
city
```
2. 使用for循环遍历值(values):
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
for value in my_dict.values():
print(value)
```
输出:
```
John
30
New York
```
3. 使用for循环遍历键值对(items):
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
for key, value in my_dict.items():
print(key, value)
```
输出:
```
name John
age 30
city New York
```
4. 使用列表推导式(list comprehension)遍历字典:
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
result = [key for key in my_dict]
print(result)
```
输出:
```
['name', 'age', 'city']
```
这些是常见的遍历字典的方法,你可以根据具体的需求选择适合的方式进行遍历。
阅读全文