python3如何遍历字典
时间: 2023-09-10 19:13:17 浏览: 42
Python3中遍历字典有两种常用的方法:
1. 使用for循环遍历字典中的键值对
```python
dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for key, value in dict.items():
print(key, value)
```
输出结果:
```
name Tom
age 18
gender male
```
2. 只遍历字典中的键或值
```python
dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
# 遍历键
for key in dict.keys():
print(key)
# 遍历值
for value in dict.values():
print(value)
```
输出结果:
```
name
age
gender
Tom
18
male
```
注意:在Python3中,字典的遍历顺序是无序的,即每次输出的结果可能不同。
相关问题
python3 遍历字典
可以使用 for 循环遍历 Python3 字典中的所有键和值,示例如下:
```python
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# 遍历所有键和值
for key, value in my_dict.items():
print(key, value)
# 遍历所有键
for key in my_dict.keys():
print(key)
# 遍历所有值
for value in my_dict.values():
print(value)
```
输出结果为:
```
name Alice
age 25
city New York
name
age
city
Alice
25
New York
```
python怎样遍历字典
在 Python 中,可以使用 for 循环遍历字典。以下是遍历字典的两种常见方法:
1. 遍历字典的键:
```python
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 遍历字典的键
for key in my_dict:
print(key)
```
输出结果为:
```
name
age
city
```
2. 遍历字典的键值对:
```python
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 遍历字典的键值对
for key, value in my_dict.items():
print(key, value)
```
输出结果为:
```
name Alice
age 25
city New York
```
在第二种方法中,使用了 `items()` 函数来获取字典的键值对。可以看到,在输出结果中,每个键值对都以键和对应的值的形式打印出来了。