What is the Best Way to Compile a List of Dictionary Terms?

Review four different ways to get all terms from a dictionary and see how they stack up in our performance test. Review four different ways to get all terms from a dictionary and see how they stack up in our performance test.

What is the Best Way to Compile a List of Dictionary Terms?

How do you compile a list of terms—or keys, for the JSON folks—from a dictionary? There are a variety of ways, but here are four different approaches and a test scenario to compare their performance.

Here’s a look at our very simple test data:

Manual Looping

The first method is looping through each term and manually appending the term to a list.

List Comprehension

The second method is using list comprehension to convert the first method into a one-liner.

Casting the .keys() Method

The third method is using the .keys() method and casting its return as a list.

List Literal Unpacking

The fourth method is using the new (as of version 3.5) list literal to unpack a dictionary.

Performance Test

So how much do these four methods differ in performance? I created a test for each method with increasing numbers of terms. Each trial tested the four methods with a dictionary that increased its number of terms by 100, up to 10,000 terms in the final trial. Here’s the code:

From the results of the test, manually looping saw the largest degradation in performance as dictionary size increased, whereas using the keys() method and list literal remained highly performant.

Given the simple syntax of the list literal, it is my new go-to method for compiling a list of keys from a dictionary.


Did I miss the technique you prefer to use? Are there other performance factors that need to be taken into account when choosing a method? Leave your comments and feedback down below!

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe