Introducing three methods of accessing dictionaries

Y2J
Release: 2017-05-18 14:04:13
Original
2306 people have browsed it

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

Method 1:

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

Result:

  a hello
  ahello
  c you
  cyou
  b how
  bhow
Copy after login

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
Copy after login

Result:

 dic[a]= hello
  dic[c]= you
  dic[b]= how
Copy after login

Method Three:

for k,v in dic.iteritems():
  print "dic[%s]="%k,v
Copy after login

Result:

  dic[a]= hello
  dic[c]= you
  dic[b]= how
Copy after login

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>
Copy after login

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

 for i in dic.iteritems():
   print i
Copy after login

Result:

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

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!