python 字典訪問的三種方法


定義字典 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')

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM