[Tutor] __getitem__ another problem

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 23 17:17:51 EST 2016


On 23/11/16 12:33, monikajg at netzero.net wrote:
> So numbermap.__getitem__ brings back 1, then 2,then 3, then 4. 
> Then it looks up 1 ,2, 3, 4 in month but there is no  key with value 1, 2, or or in 4. 
> What am I missing?

Your problem is not with getitem but with sorted.
You need to read up on how sorted uses the key parameter.

It basiocally iterates over the collection to be sorted applying the key
function to each item in the collection in turn.

It then sorts the collection based on the results. You can think of it
as turning a collection of values like

[v1,v2,v3]

into a collection of pairs where the  second item
of each pair is the result of applying the key function
to the value, like this:

[(v1,key(v1)),(v2,key(v2)),(v3,key(v3))]

And then sorting based on the second value of the pair.
Finally it returns the first value of the sorted
collection. Lets take an example where we define
a key function called mag() for magnitude:

def mag(n):
   return n if n>=0 else -n

numbers = [1,-5,2,-4]

Now if we apply sorted(numbers,mag)

sorted iterates over numbers calling mag(n) for
each number to get:

[(1,1),(-5,5),(2,2),(-4,4)]

And then sorts that list based on the second
value of each pair:

[(1,1),(2,2),(-4,4),(-5,5)]

And finally returns the first values of that sorted list:

[1,2,-4,-5]


Now your situation with a dictionary is slightly
more complex because of the added mapping between
keys and values. But for a dict it works the same
except that the key function is passed the
dictionary key each time, but the basic idea is
identical.

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list