Short answer: use the expression list(dict.keys())
.
Problem Formulation
- Given a dictionary that maps keys to values.
- Return the keys as a list.
For example:
- Given dictionary
{'Alice': 18, 'Bob', 21, 'Carl': 24}
- Return the keys as a list
['Alice', 'Bob', 'Carl']
Solution
- The
dict.keys()
method returns a list of all keys in Python 2. - The
dict.keys()
method returns adict_keys
object in Python 3 that is a more efficient representation. To convert it to a list, use the built-inlist()
constructor like so:list(dict.keys())
You can see this in action here:
>>> >>> d = {'Alice': 18, 'Bob': 21, 'Carl': 24} >>> d.keys() dict_keys(['Alice', 'Bob', 'Carl']) >>> list(d.keys()) ['Alice', 'Bob', 'Carl']
Having said this, you should ask yourself whether you really need to convert it to a list in the first place. Python iterators such as the dict_keys
object have a great advantage in terms of memory usage—you don’t instantiate the whole list in memory but piggyback on the dictionary implementation of the keys. Not converting it to a list can save you significant memory and scarce processing overview.
For example, you could simply iterate over the dict_keys
iterator rather than converting it to a list in the following example:
d = {'Alice': 18, 'Bob': 21, 'Carl': 24} for key in d.keys(): print('Key', key)
Compare this to the following version where you convert it to a list only for the purpose of iterating over it:
# This is not Pythonic! for key in list(d.keys()): print('Key', key)
The output is the same in both cases:
Key Alice Key Bob Key Carl
But as the former method without conversion requires fewer characters and function calls, as well as fewer memory usage due to the saved list data structure, it is superior to the latter with list conversion.
On the other hand, the list data structure has some more advantages such as:
- Lists can be indexed—such as in
keys[-2]
that accesses the second last key. - Lists can be slightly more efficient as generators at runtime because the i-th element doesn’t have to be generated but is already there. But this is an insignificant issue in the present scenario where you want to use the keys that are simple to iterate over—they are already there as well in the dictionary iterator.
- Lists can capture the current state of the keys for future reference in a variable if the dictionary entries change over time.
Alternative Solution with Unpacking
The asterisk operator unpacks all values in an iterable into a higher-order data structure. For example, if you unpack the dictionary into a list using the [*dict]
syntax, Python will place all keys into the dynamically created list environment. This creates a list data structure with all the dictionary keys.
The following example is analogous to the ones provided above—only using the asterisk operator for unpacking:
>>> d = {'Alice': 18, 'Bob': 21, 'Carl': 24} >>> [*d] ['Alice', 'Bob', 'Carl']
This four-character solution is obviously the shortest one—and if you love Python one-liners like me, you’d use this in your code.
Here’s my book if you’re interested in these little nasty Python tricks: π
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.