python 字典访问的三种方法小结
作者:工程师WWW 时间:2022-03-25 06:07:26
定义字典 dic = {'a':"hello",'b':"how",'c':"you"}
方法一:
for key in dic:
print key,dic[key]
print key + str(dic[key])
结果:
a hello
ahello
c you
cyou
b how
bhow
细节:
print key,dic[key],后面有个逗号,自动生成一个空格
print key + str(dic[key]),连接两个字符串,用的是加号,直接输出,中间不加逗号
方法二:
for (k,v) in dic.items():
print "dic[%s]="%k,v
结果:
dic[a]= hello
dic[c]= you
dic[b]= how
方法三:
for k,v in dic.iteritems():
print "dic[%s]="%k,v
结果:
dic[a]= hello
dic[c]= you
dic[b]= how
对比:
items()返回的是列表对象,而iteritems()返回的是iterator对象。
例如:
print dic.items() #[('a', 'hello'), ('c', 'you'), ('b', 'how')]
print dic.iteritems() #<dictionary-itemiterator object at 0x020E9A50>
深究:iteritor是迭代器的意思,一次返回一个数据项,直到没有为止
for i in dic.iteritems():
print i
结果:
('a', 'hello')
('c', 'you')
('b', 'how')
来源:https://blog.csdn.net/weiwangchao_/article/details/70578087
标签:python,字典,访问
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使链接具有最大化、最小化的功能代码
2008-02-24 16:43:00
在任意字符集下正常显示网页的方法二(续)
2023-11-22 17:36:14
MySQL安全性指南(3)(转)
2010-07-26 13:07:00
多表关联同时更新多条不同的记录方法分享
2011-11-03 17:34:25
Python configparser模块操作代码实例
2021-11-05 18:48:08
修改SQL Server 2005 sa用户密码的方法
2008-12-10 14:41:00
ASP.NET在IIS一些问题经验总结
2007-08-07 15:42:00
python Multiprocessing.Pool进程池模块详解
2023-08-25 09:24:59
asp 删除数据并同时删除图片的代码
2011-02-28 10:39:00
一个Access数据库数据传递的实例方法
2008-11-28 16:24:00
python实现超市扫码仪计费
2023-01-11 03:53:31
![](https://img.aspxhome.com/file/2023/0/66860_0s.png)
Python Django 命名空间模式的实现
2023-10-06 05:34:28
![](https://img.aspxhome.com/file/2023/7/72777_0s.png)
解析python中的jsonpath 提取器
2021-11-18 23:06:04
Python浅析匿名函数lambda的用法
2022-07-19 18:29:29
![](https://img.aspxhome.com/file/2023/3/81493_0s.png)
ASP.NET中使用SQL存储过程的方法
2007-08-24 09:31:00
python进阶教程之文本文件的读取和写入
2023-08-03 03:27:47
SQL SERVER如何判断某个字段包含大写字母
2023-07-01 21:19:12
eWebEditor不支持IE8的解决方法
2009-11-02 10:59:00
![](https://img.aspxhome.com/file/UploadPic/200911/2/200911211534338s.jpg)
5步让你的CSS样式表成功减肥
2009-08-02 21:27:00
![](https://img.aspxhome.com/file/UploadPic/20098/2/css-01-85s.gif)
python实现协同过滤推荐算法完整代码示例
2023-10-11 00:29:05
![](https://img.aspxhome.com/file/2023/1/69491_0s.png)