给定字典dic如下: dic = { 'python': 90, 'java': 95 } 用两种方法遍历字典dic
时间: 2024-02-15 11:31:21 浏览: 60
python 字典访问的三种方法小结
方法一:使用for循环遍历字典
```python
dic = {'python': 90, 'java': 95}
# 遍历字典的key和value
for key, value in dic.items():
print(key, value)
# 遍历字典的key
for key in dic.keys():
print(key)
# 遍历字典的value
for value in dic.values():
print(value)
```
方法二:使用字典推导式遍历字典
```python
dic = {'python': 90, 'java': 95}
# 遍历字典的key和value
kv = [(key, value) for key, value in dic.items()]
print(kv)
# 遍历字典的key
keys = [key for key in dic.keys()]
print(keys)
# 遍历字典的value
values = [value for value in dic.values()]
print(values)
```
阅读全文