Python - How To Get Dictionary Keys as a List in Python

ID : 173

viewed : 138

Tags : PythonPython Dictionary

vote vote


Getting a view of as a sequence is an everyday use case in Python programming.

There are several approaches to achieve it, each with different performance characteristics.

dict.keys() to Get Python Dictionary Keys

The function returns dict_keys - an iterable view of the dictionary’s keys.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> state_capitals.keys() dict_keys(['California', 'Pennsylvania', 'Texas']) 

You can iterate over dict_keys directly without converting it into a list. For many use cases, dict_keys can be dropped instead of a list in APIs, and it will work.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> for state in state_capitals.keys(): ...   print(state) ... California Pennsylvania Texas 

If you need to work on dictionary keys strictly as on lists, for example, if you want to be able to use an index to read a particular key from the sequence, you should convert dict_keys into a list first.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> list(state_capitals.keys()) ['California', 'Pennsylvania', 'Texas'] 

Note that calling dict.keys() is optional if you want to get keys as a list. Since Python dictionaries are iterable over their keys, you can pass a dictionary itself into a list constructor.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> list(state_capitals) ['California', 'Pennsylvania', 'Texas'] 

Loops to Get Python Dictionary Keys

A peculiar property of dictionaries in Python is that when you iterate over them, you iterate of their keys. Thus you can collect all dictionary keys simple by iterating over it.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> keys = [] >>> for key im state_capitals: ...   keys.append(key) ... >>> keys ['California', 'Pennsylvania', 'Texas'] 

List Comprehensions to Get Python Dictionary Keys

A syntactic improvement over using loops can be using Python’s . With list comprehensions, you can condense the above loop into a one-liner.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> keys = [key for key in state_capitals] >>> keys ['California', 'Pennsylvania', 'Texas'] 

Python Dictionary Unpacking * Operator to Get the Keys

Starting with Python 3.5, we can use the unpacking * operator to get a hold over dictionary keys. This feature was introduced with - Additional Unpacking Generalizations.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> keys = [*state_capitals] >>> keys ['California', 'Pennsylvania', 'Texas'] 

The upside of this approach is that you can unpack your dictionary keys into other collections beyond lists, such as tuples or sets.

>>> state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'} >>> keys_tuple = *state_capitals, >>> keys_tuple ('California', 'Pennsylvania', 'Texas') >>> keys_set = {*state_capitals} >>> keys_set {'California', 'Pennsylvania', 'Texas'} 

Compare Runtime Performance

Runtime performances of each of the above approaches vary.

>>> from timeit import timeit >>> timeit("list(state_capitals.keys())", setup="state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'}") 0.25394885599962436 >>> timeit("list(state_capitals)", setup="state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'}") 0.17995373999929143 >>> timeit("for key in state_capitals: keys.append(key)", setup="keys = []; state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'}") 0.25294865500018204 >>> timeit("[key for key in state_capitals]", setup="state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'}") 0.2447525150000729 >>> timeit("[*state_capitals]", setup="state_capitals = {'California': 'Sacramento', 'Pennsylvania': 'Harrisburg', 'Texas': 'Austin'}") 0.0962776809992647 

As follows from the timings above, the unpacking * operator is the fastest.

Prefer it, unless you have a good reason to fall back to any of the other approaches.

  • Related HOW TO?