Explain Codes LogoExplain Codes Logo

How do I return dictionary keys as a list in Python?

python
dict-keys
python-idioms
performance
Anton ShumikhinbyAnton Shumikhin·Aug 22, 2024
TLDR

If you need dictionary keys returned as a list, you can employ list(my_dict) or apply my_dict.keys() within a list comprehension. Here's the nitty-gritty:

my_dict = {'a': 1, 'b': 2} keys_list = list(my_dict) # No keys were harmed in making this list => ['a', 'b'] # or keys_list = [key for key in my_dict] # Who let the keys out? => ['a', 'b']

Both expressions return the key list in blazing speed.

The Mechanics behind the Scenes

Keys Liberation with Unpacking

Python 3.5+ astounds with a sudoku level shortcut for unpacking collections:

keys_list = [*my_dict] # Unleashes the keys in the wild => ['a', 'b']

The Tale of dict_keys

Despite dict_keys received from my_dict.keys() masquerading as a list, they aren't. They pull off a high-wire act as view objects, providing a live view on the dictionary keys playing field.

Efficiency Realm and The Iteration Marvel

Straight looping over my_dict or entrusting dict_keys with loop duty is RAM-neat, as it abstains from birthing a list:

for key in my_dict: # No list spawned here, move along # exec magic with key

Deep Dive into Key Extraction

Battle of Ages: Python 2 vs Python 3

Create an alert for version variances: In Python 2 keys() operation emits a list, but in Python 3 it emits a dict_keys beacon.

Key Order Chronicles

Bows to Python 3.7+; dictionaries steward insertion order. Version holdouts, take note! Key order when converging to a list is not insured.

The Performance Saga

Got a sizable collection to parse? Iterating over dict_keys could have performance perks compared to first transforming to a list.

Pythonic Paradigms

Python idioms askew? Bracket arms with zip() for iterating over a pair of dictionaries simultaneously, dodging separate list creation.

The Iterable Illusion & Duck Typing

Mirror mirror on the wall, does dict_keys behave like a sequence after all? Absolutely! A taste of the duck typing in Python; quacks like a list, iterate over it!

Beware of the 'list' Impostor

Alas! While dict_keys is iterable, it neither supports item assignments nor the append method, shying away from its list alter ego.