python 字典访问的三种方法
2015-09-07 22:09
471 查看
定义字典 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')
文章转自:http://www.cnblogs.com/kaituorensheng/archive/2012/09/05/2672711.html
方法一:
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')
文章转自:http://www.cnblogs.com/kaituorensheng/archive/2012/09/05/2672711.html
相关文章推荐
- 《笨方法学python-6》之lambda
- “Python"学习笔记(五)(控制流)
- NumPy教程(转)
- wxpython初学者(三) 之flexgirdsizer,TextEntryDialog,SingleChoiceDialog
- python的urllib2包基本使用方法
- wxpython初学者(三)
- “Python"学习笔记(四)(函数二)
- 2 Dimension list (list中的list)game 2048 part2
- Python之面向对象初体验
- python会什么比c慢
- Python 之 Post 登陆 Dz 论坛
- mac下安装MYSQL-python
- 使SourceInsight支持Python语言的方法
- python实现并行爬虫
- python——ADSL拨号程序
- 将 Sublime 3 打造成 Python/Django IDE
- Python的函数参数传递:传值?引用?
- python中判断语句
- python_正则表达式
- python-文件替换二进制脚本