python 字典访问的三种方法
2015-07-21 11:28
183 查看
定义字典 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')
/article/4722557.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')
/article/4722557.html
相关文章推荐
- Python
- Python学习打算
- Python sort sorted函数详解
- Python入门教程 超详细1小时学会Python
- 详解Python的Django框架中Manager方法的使用
- PyQt环境的搭建:安装python+pyqt+eric
- python 字典之一key->多值
- 计划两个月刷刷 OReilly.Introducing.Python
- python列表生成式
- python基础教程总结8——特殊方法,属性,迭代器,生成器,八皇后问题
- [Tip] Install OpenCV3.0.0 for python3.4.3 under ubuntu15.04
- 深刻理解Python中的元类
- python线程锁
- Python原型模式
- IPython 新建窗口绘图
- Python下opencv使用笔记(十)(图像频域滤波与傅里叶变换)
- Python 学习笔记之语法(一)
- 一个简单的python闭包例子
- Python 线程和定时器
- Google's Python Class(五)——Python 字典和文件