python 遍历dict
时间: 2023-12-26 08:28:54 浏览: 30
以下是两种遍历字典的方法:
1. 使用for循环遍历字典的键:
```python
book = {'title': 'Python', 'author': '--', 'press': '人生苦短,我用python'}
for key in book.keys():
print(key) # 输出结果:title author press
```
2. 使用for循环遍历字典的值:
```python
book = {'title': 'Python', 'author': '--', 'press': '人生苦短,我用python'}
for value in book.values():
print(value) # 输出结果:Python -- 人生苦短,我用python
```
相关问题
python 遍历dict
在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']
```
这些是常见的遍历字典的方法,你可以根据具体的需求选择适合的方式进行遍历。
python遍历dict
遍历Python中的字典可以使用for循环和items()方法,示例代码如下:
```
dict = {'name': 'John', 'age': 25, 'gender': 'male'}
# 遍历键值对并打印结果
for key, value in dict.items():
print(key, ':', value)
# 遍历键并打印结果
for key in dict.keys():
print(key)
# 遍历值并打印结果
for value in dict.values():
print(value)
```
希望能帮助到您,有什么其他问题可以继续问我。