The value of the Python iteration Dict

Source: Internet
Author: User

The value of the iteration Dict

1:values ()

2:itervalues ()

3:forkey inDi:

    print (Di[key])

We have learned that the Dict object itself is an iterative object , iterating the dict directly with a for loop, and can get a key for dict each time.

What should we do if we want to iterate over the value of the Dict object?

The Dict object has a values () method , which converts the dict into a list that contains all value, so that we iterate over each value of Dict:

D = {' Adam ':}print, ' Lisa ': $, ' Bart ': D.values () # [59], 59]for V in D.values ():    print v# 85# 95#

If you read the Python document carefully, you can also see that dict, in addition to the values () method, has a itervalues ( ) method that replaces The Itervalues () method with the The values () method, the iteration effect is exactly the same:

D = {' Adam ': +, ' Lisa ': $, ' Bart ':}print d.itervalues () # <dictionary-valueiterator object at 0x106adbb50>for V in D.itervalues ():    print v# 85# 95# 59

What is the difference between the two methods?

1. The values () method actually converts a dict to a list containing value.

2. However, the itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.

3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, thefor loop can be used to iterate beyond list,tuple,str. Unicode,dict, and so on , any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.

If an object says that it can iterate, then we iterate it directly with a for loop, which is an abstract data operation that does not require any data inside the iteration object.

The value of the Python iteration Dict

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.