Jiew Meng
Jiew Meng

Reputation: 88197

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>
    

Upvotes: 3

Views: 641

Answers (3)

wim
wim

Reputation: 362557

First of all, please avoid calling a variable dict, for you can shadow the built-in this way.

1) I don't believe so. If you want sorted dict, just use OrderedDict from collections module.

2) You should read it as an anonymous function, which given an input argument key, will return the object mydict[key]. It would be equivalent to:

def foo(key):
  # assume mydict is in scope
  return mydict[key]

3) Assuming your variable d here is a dict, it will return a list of keys in the dictionary sorted by their corresponding values from d. It means that the function d.get() is called for whatever is in d when iterating, and the list will be sorted by the return values of d.get rather than by the objects themselves.

Upvotes: 3

campos.ddc
campos.ddc

Reputation: 771

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.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

  1. No. Dictionaries are ordered by the hash of their keys, and there is no guarantee that the hash algorithm won't change between versions or implementations.

  2. Everything between lambda and : is the arguments. Everything after the : is the returned expression.

  3. The get method of the object bound to d. In dict objects it returns the value if the key exists, otherwise the passed default or None.

Upvotes: 4

Related Questions