Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods for sorting a dictionary

I am referring to the question: https://stackoverflow.com/a/575889/292291

  1. 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'}
    
  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?

  3. 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>
    
like image 499
Jiew Meng Avatar asked May 18 '26 04:05

Jiew Meng


1 Answers

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.

like image 57
campos.ddc Avatar answered May 19 '26 18:05

campos.ddc