Three ways to access the dictionary

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

method one:

for key in dic:

  print key,dic[key]

  print key + str(dic[key])

result:

  a hello
  ahello
  c you
  cyou
  b how
  bhow

detail:

print key, dic [key], followed by a comma, a space generated automatically

print key + str (dic [key]), two strings connected with the plus sign is output directly, without intermediate comma

Method Two:

for (k,v) in dic.items():

  print "dic[%s]="%k,v

result:

  dic[a]= hello
  dic[c]= you
  dic[b]= how

Method three:

for k,v in dic.iteritems():

  print "dic[%s]="%k,v

result:

  dic[a]= hello
  dic[c]= you
  dic[b]= how

Compared:

items () returns a list of objects, iteritems () returns an iterator object. E.g:

print dic.items()        #[('a', 'hello'), ('c', 'you'), ('b', 'how')]

print dic.iteritems()   #<dictionary-itemiterator object at 0x020E9A50>

Get to the bottom: iteritor iterator is meant to go back once a data item, I do not know so far

 for i in dic.iteritems():
   print i
结果:('a', 'hello')
        ('c', 'you')
        ('b', 'how')

Guess you like

Origin www.cnblogs.com/mainstream/p/11031995.html