Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding dictionary.get in Python

I was reading this really helpful SO post on sorting dictionaries. One of the most popular answers suggests this:

sorted(dict1, key=dict1.get)

While this seems to work perfectly fine, I don't get the key=dict1.get part.

What exactly is get here and what does it do?

I am only familiar with using get('X') to extract X from a dictionary... And I couldn't find anything in the docs on dictionaries and stdtypes, so any pointers are much appreciated!

NB here is what they have to say about get(), or is this something entirely different? Thanks!

get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError

like image 471
patrick Avatar asked Dec 01 '22 12:12

patrick


2 Answers

The key argument to sorted is a callable (e.g. a function) which takes one argument.

By default, sorted sorts the values by comparing them to each other. For example:

sorted([2, 3, 1])   # returns [1, 2, 3]

This is because 1 < 2 < 3.

On the other hand, if a different value should be used for comparison, that can be defined with key. For example, to sort strings by length, one coudld do:

def string_length(s):
    return len(s)

sorted(['abcd', 'efghi', 'jk'], key=string_length)  # returns ['jk', 'abcd', 'efghi']

This is because string_length('jk') < string_length('abcd') < string_length('efghi').

But instead of a funcion, you can pass any other callable. In your example, that is dict1.get, so for each key in the dict, dict1.get(key) will be executed and the result of that will be used in comparison.

dict1 = {'a':3, 'b':1, 'c':2}

sorted(dict1, key=dict1.get) # returns ['b', 'c', 'a']

This is because dict1.get('b') < dict1.get('c') < dict1.get('a').

like image 123
zvone Avatar answered Dec 10 '22 12:12

zvone


sorted(dict1, key=dict1.get)

is a less verbose and more pythonic way of saying:

sorted(dict1, key=lambda x: dict1[x] if x in dict1 else None)

Bear in mind that iterating on a dictionary will return its keys, therefore the get method takes arguments which are the dictionary keys, which in turn returns the value that key is pointing to.

TL;DR It's a simple way of saying sort the dictionary keys using the values as the sort criteria.

like image 26
Moses Koledoye Avatar answered Dec 10 '22 11:12

Moses Koledoye