简体   繁体   中英

How does this code sort a dictionary?

I was looking for ways to sort a dictionary and came across this code on a SO thread :

import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))

How does this code work? When I call iteritems() over a dictionary I get this:

<dictionary-itemiterator object at 0xf09f18>

I know that this is a reference, but how do you use it? And afaik, in sorted(a,b), as is supposed to be the thing you want to sort, and b would be the indicator for sorting right? How does itemgetter(1) work here?

operator.itemgetter(1) is equivalent to lambda x: x[1] . It's an efficient way to specify a function that returns the value at index 1 of its input.

.iteritems() is a method of a dictionary that returns an iterator over the entries in the dictionary in (key,value) tuple form.

  • iteritems() is just like items() , except it returns an iterator rather than a list. For large dictionaries, this saves memory because you can iterate over each individual element without having to build up the complete list of items in memory first.
  • sorted accepts a keyword argument key which is a function used to determine what to compare by when sorting something. In this case, it is using operator.itemgetter , which is like the function version of doing something[1] . Therefore, the code is sorting on the [1] item of the tuples returned by items() , which is the value stored in the dictionary.

Most python built-ins which deal with lists or list like objects also accept iterators, these are like a pointer into the list, which you can advance to the next item in the list with the next() member function. This can be very convenient for infinite lists or very large lists, (either many elements or very large elements,) to keep memory usage down. See http://docs.python.org/library/stdtypes.html#iterator-types

iteritems() gives an iterator into the list of items in the dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM