python 字典访问的三种方法
2017-04-24 11:36
260 查看
定义字典 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')
方法一:
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字典访问的三种方法
- python字典访问的三种方法
- python 字典访问的三种方法
- python 字典访问的三种方法
- python字典访问的三种方法
- python 字典访问的三种方法
- python 字典访问的三种方法
- 【python】字典及其创建和访问以及方法(关联数组或哈希表)
- python使用点操作符访问字典(dict)数据的方法
- 【转载】Python中如何高效实现两个字典合并,三种方法比较。
- python实现字典的键值对互换的三种方法
- 访问 Microsoft SQL Server 元数据的三种方法
- python判断某个对象是否可以做一个字典的键多方法
- 线程间操作无效: 从不是创建控件的线程访问它的三种方法
- python有三种导入模块的方法
- Struts2中Action访问Servlet API的三种方法
- 遍历python字典几种方法
- Action 访问Servlet API的三种方法
- Python 列表和字典的一些方法
- SQL2008报表三种实现Reporting Service2008匿名访问的方法(转)