0

I have created a dict in python and would like to find the max value. I experimented with max with key= anonymous function. I certainly implemented wrong, but somehow the code ran and I ended up with output of a key, which does not make sense to me at all. Could you someone please explain to me why it works and how? Thank you.

Q['state1']={'zone':20,'left':50,'right':89,'forward':34}
qmax=max(Q['state1'],key=lambda x: x[1]) %this returns 'forward'
qmax=max(Q['state1'],key=lambda x: x[0]) %this returns 'zone'

2 Answers 2

2

If you pass a dictionary to max, it iterates over the dictionary keys (which is a list of strings here), and since you've specified a comparator function, the comparison is now done on x[1] (in the first line) which happens to be the second character of each key, and x[0] (in the second line) which happens to be the first character of each key.

So, for example, you have a list of keys:

['forward', 'zone', 'right', 'left']  

Note that this list could be returned in any order, because dictionaries have no ordering. Now, the basis for choosing the max is the 2nd character, so you choose based on:

['f o rward', 'z o ne', 'r i ght', 'l e ft'] 

And it just so happens that, for your CPython implementation, forward is returned before zone (although either one could have been returned, depending on the order in which keys were returned from the dictionary).

Sign up to request clarification or add additional context in comments.

1 Comment

Note: Because it's a string keyed dictionary, it's not even that the implementation defines the order, nor the order of element insertions and deletions. The hash perturbation done as a security measure (for strings, bytes and datetimes) means the order can vary from run to run, on the same interpreter, building the dictionary in the exact same way; each new interpreter launch gets a different hash seed, so string keys reorder.
1

You're iterating the (string) keys and indexing them in your lambda to make sort keys from specific letters in the keys, not iterating the key/value pairs and using a sort key of either dict key or value. I'm guessing you intended to find the max based on dict key or value, in which case you'd want to call .items() (or to avoid a temporary on Py2.7 .viewitems()):

max(Q['state1'].viewitems(), key=lambda x: x[1])  # gets ('right', 89)
max(Q['state1'].viewitems(), key=lambda x: x[0])  # gets ('zone', 20)

Alternatively, if you don't need the pairing at all, skip the key, and just iterate what you care about directly:

max(Q['state1'].viewvalues())  # gets 89
max(Q['state1'])  # gets 'zone'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.