python 字典访问 items()和iteritems()的区别
2015-08-15 10:31
711 查看
python 字典访问的三种方法
定义字典 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')
相关文章推荐
- python sort和sorted使用详解
- Python异常管理
- Python开发环境的搭建(win7)
- python 数值类型,判断类型
- python快速使用(三)类、异常
- Python Version 2.7 required which was not found in the registry 问题解决
- 3.Python 条件if
- 3.Python多线程程序Ctrl+C的优雅终止
- Python安装NumPy,matplotlib等方法
- python自动化运维――OMserver平台Web服务端部署过程
- Python的中国镜像网站--下载资源更快
- 零基础学python-3.3 标识符
- 零基础学python-3.3 标识符
- 零基础学python-3.2 变量赋值
- 零基础学python-3.2 变量赋值
- 零基础学python-3.1 python基本规则和语句
- 零基础学python-3.1 python基本规则和语句
- 零基础学python-2.24 一些常用函数
- 零基础学python-2.24 一些常用函数
- 零基础学python-2.23 模块