I am referring to the question: https://stackoverflow.com/a/575889/292291
If I use integers as the key, it appears I am guaranteed a sorted order?
>>> dict = { 2: "list 2", 0: "list 0", 1: "list 1" }
>>> dict
{0: 'list 0', 1: 'list 1', 2: 'list 2'}
In sorted(mydict, key=lambda key: mydict[key]), how do I interpret or read the lambda? I don't understand that part since I'm new to lambdas. What does key: and mydict[key] refer to?
In sorted(d, key=d.get) what does d.get refer to? If I do:
>>> dict.get
<built-in method get of dict object at 0x1d27830>
1- Dicts never guarantee an order, sometimes it may even look like it does, but get enough numbers in there and you'll see they don't (this is because of the way that hashes are obtained for each key)
2- These two are the same:
lambda key: mydict[key]
def temp_function(key):
return mydict[key]
Basically, you are creating a temporary function that receives key as a parameter, and returns mydict[key]
3- The second argument of sorted refers to the function that will be called, passing the current dict key. The value returned by this will be used to determine the order of your sorted dict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With