Python | Intermediate | Priority Flashcards

1
Q

How to sort a dictionary by values in descending order.

A
[(k, d[k]) for k in sorted(d, key=d.get, reverse=True)]
sorted(d.items(), key=itemgetter(1), reverse=True)
sorted(d.items(), key=lambda x: x[1], reverse=True)
# To keep using as a dictionary, wrap in an OrderedDict:
OrderedDict(sorted(…))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Example of how to make a class a contect manager?

2.3 p31

A

(See source material.)

2.3 p31

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does a double leading underscore like “__var” do?

2.4 p47

A

Triggers name mangling when used in a class context. Enforced by the Python interpreter.

2.4 p47

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create a factory function?

3.1 p66

A

Define an inner function that returns a function.

3.1 p66

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are (lexical) closures?

3.1 p67

A

Functions can be nested and they can capture and carry some of the parent function’s state with them. Functions that do this are called closures.

3.1 p67

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What’s a one-sentence definition of a decorator? In what order are decorators applied?

A

A decorator is a callable that takes a callable as input and returns another callable. Bottom to top.

Python Tricks 3.3 The Power of Decorators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Putting a * before an iterable in a function call will do what? Putting a **?

A

Unpack it and pass its elements as separate positional arguments to the called function. Unpacks by matching up dictionary values and function arguments based on the dictionary keys.

Python Tricks 3.5 Function Argument Unpacking

How well did you know this?
1
Not at all
2
3
4
5
Perfectly