python 字典访问的三种方法
2012-09-05 23:42
323 查看
定义字典 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= how
[b]方法三:
for k,v in dic.iteritems():
print "dic[%s]="%k,v
结果:
dic[a]= hello
dic[c]= you
dic= how
[b]对比:
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')
方法一:
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= how
[b]方法三:
for k,v in dic.iteritems():
print "dic[%s]="%k,v
结果:
dic[a]= hello
dic[c]= you
dic= how
[b]对比:
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字典访问的三种方法
- python 字典访问的三种方法
- python 字典访问的三种方法
- python字典访问的三种方法
- python 字典访问的三种方法
- python字典访问的三种方法
- python 字典访问的三种方法
- 【转载】Python中如何高效实现两个字典合并,三种方法比较。
- python使用点操作符访问字典(dict)数据的方法
- python实现字典的键值对互换的三种方法
- 【python】字典及其创建和访问以及方法(关联数组或哈希表)
- python进阶学习笔记(四)——python中访问限制、创建类属性、定义实例方法、定义类方法、类的继承
- Python下访问MYSQL的方法总结
- 浅谈python类属性的访问、设置和删除方法
- python中dict字典的查询键值对 遍历 排序 创建 访问 更新 删除基础操作方法
- Python遍历字典dict的几种方法
- Python中表示字符串的三种方法
- 常用的Python字典方法
- opencv访问像素的三种方法
- python生成密码字典的方法