hans-201506

python字典访问的三种方法

定义字典 dic = {\'a\':"hello",\'b\':"how"}

法一:

for key in dic:
  print key,dic[key]         # a hello     输出中间有空格
  print key + str(dic[key])  # ahello      输出中间没空格

法二:

for (k,v) in dic.items():
  print "dic[%s]="%k,v      #dic[a]= hello

法三:

for k,v in dic.iteritems():
  print "dic[%s]="%k,v   #  dic[a]= hello

法二和法三对比:

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\')

 

 

原文:http://www.cnblogs.com/kaituorensheng/archive/2012/09/05/2672711.html

分类:

技术点:

相关文章:

  • 2021-08-19
  • 2021-07-02
  • 2021-09-07
  • 2021-06-19
  • 2021-06-12
  • 2021-09-07
  • 2021-10-07
猜你喜欢
  • 2021-11-15
  • 2021-11-15
  • 2021-10-07
  • 2021-10-07
  • 2021-10-07
  • 2021-04-14
  • 2021-12-10
相关资源
相似解决方案