python 遍历字典
时间: 2023-12-10 09:34:54 浏览: 83
python遍历字典
5星 · 资源好评率100%
以下是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)
```
阅读全文