Home >Backend Development >Python Tutorial >Introducing three methods of accessing dictionaries

Introducing three methods of accessing dictionaries

Y2J
Y2JOriginal
2017-05-18 14:04:132418browse

Definition dictionary dic = {'a':"hello",'b':"how",'c':"you"}

Method 1:

for key in dic:
  print key,dic[key]
  print key + str(dic[key])

Result:

  a hello
  ahello
  c you
  cyou
  b how
  bhow

Details:

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

print key + str(dic[key]), connection Two strings , using the plus sign, output directly without commas in between

Method 2:

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

Contrast:

items() returns a list object, while iteritems() returns an iterator object . For example:

print dic.items()        #[('a', 'hello'), ('c', 'you'), ('b', 'how')]
print dic.iteritems()   #<dictionary-itemiterator object at 0x020E9A50>

Digging deeper: iteritor means iterator, one data item at a time, until it lasts

 for i in dic.iteritems():
   print i

Result:

(&#39;a&#39;, &#39;hello&#39;)
(&#39;c&#39;, &#39;you&#39;)
(&#39;b&#39;, &#39;how&#39;)

[Related recommendations]

1. Special recommendation: "php Programmer Toolbox" V0.1 version download

2. Python free video tutorial

3. Basic introduction to Python items() method

4. Example of item() function in Python traversing dictionary

5. Detailed explanation of the usage of items() series functions in Python

6. The difference between iteriitems and items in sorted

The above is the detailed content of Introducing three methods of accessing dictionaries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn