python遍历字典中的values
时间: 2023-12-29 11:45:16 浏览: 83
可以使用字典的values()方法将所有的值提取出来存储到一个列表中,然后对列表进行遍历操作。下面是一个简单的示例代码:
```
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
values = list(my_dict.values())
for value in values:
print(value)
```
输出结果为:
```
value1
value2
value3
```
相关问题
python 遍历字典
以下是Python遍历字典的几种方法:
1.使用for循环遍历字典的键值对
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for name, language in favorite_languages.items():
print(name + "'s favorite language is " + language)
```
2.使用for循环遍历字典的键
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for name in favorite_languages.keys():
print(name)
```
3.使用for循环遍历字典的值
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for language in favorite_languages.values():
print(language)
```
4.使用列表推导式遍历字典的键值对
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
print([(name, language) for name, language in favorite_languages.items()])
```
5.使用列表推导式遍历字典的键
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
print([name for name in favorite_languages.keys()])
```
6.使用列表推导式遍历字典的值
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
print([language for language in favorite_languages.values()])
```
7.使用字典方法items()遍历字典的键值对
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for item in favorite_languages.items():
print(item)
```
8.使用字典方法keys()遍历字典的键
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for key in favorite_languages.keys():
print(key)
```
9.使用字典方法values()遍历字典的值
```python
favorite_languages = {'Tom': 'python', 'Jerry': 'c', 'Mickey': 'ruby'}
for value in favorite_languages.values():
print(value)
```
python遍历字典
可以使用 for 循环遍历字典中的键值对,示例代码如下:
```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
```
另外,如果只需要遍历字典的键或值,可以使用 `keys()` 或 `values()` 方法,示例代码如下:
```python
# 遍历字典的键
for key in my_dict.keys():
print(key)
# 遍历字典的值
for value in my_dict.values():
print(value)
```
阅读全文