Three ways to access the Python dictionary

Source: Internet
Author: User

Definition dictionary dic = {' A ': ' Hello ', ' B ': ' How ', ' C ': ' You '}

Method One:

For key in DIC:

Print Key,dic[key]

Print key + str (Dic[key])

Results:

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]), connecting two strings, with a plus sign, direct output, without commas in the middle

Method Two:

for (K,V) in Dic.items ():

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

Results:

dic[a]= Hello
dic[c]=
dic[b]= How

Method Three:

For k,v in dic.items (): #Python3中已经废除iteritems, use items instead

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

Results:

dic[a]= Hello
dic[c]=
dic[b]= How

Items () returns a Iterator object. For example:

Print Dic.items () #<dictionary-itemiterator object at 0x020e9a50>

Drill Down: Iteritor is the meaning of iterators, one time to back up a data item, know no so far

For I in Dic.items ():
Print I
Result: (' A ', ' hello ')
(' C ', ' you ')
(' B ', ' how ')

Three ways to access the Python dictionary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.