python字典访问
时间: 2023-11-03 08:01:18 浏览: 78
在Python中,我们可以使用for循环来遍历字典。有几种方法可以访问字典的键和值:
方法一:
```
dic = {'a':"hello",'b':"how",'c':"you"}
for key in dic:
print(key, dic[key])
```
方法二:
```
dic = {'a':"hello",'b':"how",'c':"you"}
for (k,v) in dic.items():
print("dic[%s]=" % k, v)
```
方法三:
```
dic = {'a':"hello",'b':"how",'c':"you"}
for k,v in dic.items():
print("dic[%s]=" % k, v)
```
这些方法都可以用来访问字典的键和值。第一种方法使用key变量来遍历字典的键,然后通过key来获取对应的值。第二种和第三种方法使用元组来同时遍历键和值。
阅读全文
相关推荐











