How to convert a dictionary to a list in Python
Learn how to convert a Python dictionary to a list with various methods. Explore tips, real-world uses, and common error debugging.

Developers frequently need to convert a Python dictionary to a list. This process allows you to manipulate dictionary data in an ordered sequence, which is useful for many programming scenarios.
In this article, you'll find several conversion techniques using methods like .items(), .keys(), and .values(). We'll also share practical tips, explore real-world applications, and provide debugging advice to help you handle data transformations effectively.
Converting a dictionary to a list with list()
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict)
print(keys_list)--OUTPUT--['a', 'b', 'c']
Applying the list() constructor directly to a dictionary is a straightforward way to extract its keys. By default, iterating over a dictionary processes its keys, so list(my_dict) gives you a list containing only the keys, preserving their insertion order in modern Python versions.
You'll find this approach particularly useful when your task only involves the keys. For instance, you might need to sort them or check if a specific key exists, and you don't need the corresponding values for the operation.
Basic dictionary to list conversions
While the list() constructor is a quick way to get keys, Python's dictionary methods offer more targeted ways to extract keys, values, or key-value pairs.
Getting a list of keys with dict.keys()
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
print(keys_list)--OUTPUT--['a', 'b', 'c']
The dict.keys() method offers an explicit way to work with a dictionary's keys. It returns a dynamic "view object" that displays the keys. This means if the dictionary changes, the view reflects those changes in real time.
- To get a fixed list of keys at a specific moment, you wrap the view object with the
list()constructor. - This method improves code readability by clearly signaling your intent to operate on the dictionary's keys.
Getting a list of values with dict.values()
my_dict = {'a': 1, 'b': 2, 'c': 3}
values_list = list(my_dict.values())
print(values_list)--OUTPUT--[1, 2, 3]
When you only need the values from a dictionary, the dict.values() method is your go-to tool. It isolates the values and provides a view object, which you can convert into a standard list by wrapping it with the list() constructor.
- This approach is ideal when you need to perform calculations—like finding the sum or average—on the numerical data within a dictionary.
- The resulting list preserves the order of the values as they appear in the dictionary, which is a reliable feature in modern Python.
Getting a list of key-value tuples with dict.items()
my_dict = {'a': 1, 'b': 2, 'c': 3}
items_list = list(my_dict.items())
print(items_list)--OUTPUT--[('a', 1), ('b', 2), ('c', 3)]
When you need to preserve the relationship between keys and their values, dict.items() is the perfect tool. It bundles each key with its corresponding value into a tuple. Converting the result to a list gives you a list of these key-value tuples, maintaining their original association.
- This is incredibly useful when you need to iterate over both keys and values at the same time.
- It allows you to sort or filter the dictionary's contents based on either the key or the value while keeping the pairs intact.
Advanced dictionary to list techniques
Beyond simply extracting keys, values, or items, you can use more powerful methods to transform your dictionary data during the conversion process itself.
Using list comprehensions for custom transformations
my_dict = {'a': 1, 'b': 2, 'c': 3}
formatted_list = [f"{key}:{value}" for key, value in my_dict.items()]
print(formatted_list)--OUTPUT--['a:1', 'b:2', 'c:3']
List comprehensions offer a concise and readable way to create a new list while transforming data on the fly. They essentially pack a for loop into a single, elegant line, making your code more efficient.
- The expression
[f"{key}:{value}" for key, value in my_dict.items()]iterates through each key-value pair from the dictionary. - For each pair, it applies a custom format—in this case, creating a string with an f-string—and adds the result to the new list.
This technique is perfect when you need more than just the raw keys or values and want to structure the output in a specific way.
Applying map() with lambda functions
my_dict = {'a': 1, 'b': 2, 'c': 3}
doubled_values = list(map(lambda item: (item[0], item[1]*2), my_dict.items()))
print(doubled_values)--OUTPUT--[('a', 2), ('b', 4), ('c', 6)]
The map() function provides a functional approach to transforming data. It applies a given function to every item in an iterable, such as the key-value pairs from my_dict.items().
In this example, a lambda function is used to define the transformation on the fly.
- The
lambdafunction,lambda item: (item[0], item[1]*2), processes each key-value tuple. - For each
item, it creates a new tuple containing the original key (item[0]) and a doubled value (item[1]*2). - The
list()constructor then collects these transformed tuples from themapobject into a final list.
Creating nested lists from dictionary entries
my_dict = {'a': 1, 'b': 2, 'c': 3}
nested_list = [[key, value] for key, value in my_dict.items()]
print(nested_list)--OUTPUT--[['a', 1], ['b', 2], ['c', 3]]
You can also use a list comprehension to create a nested list. This technique is handy when you need each key-value pair to be a mutable list instead of an immutable tuple, which allows for in-place modifications.
- The expression
[[key, value] for key, value in my_dict.items()]iterates through the dictionary's items. - For each pair, it creates a new inner list, like
['a', 1]. This is useful because, unlike tuples, you can modify the contents of these lists later on.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly.
Instead of piecing together techniques, you can use Agent 4 to build the complete application you have in mind. It handles the code, databases, APIs, and deployment directly from your description. You could build tools that use these dictionary conversions, like:
- A configuration file parser that converts a dictionary of settings into a formatted list for a status dashboard.
- An inventory management utility that processes a dictionary of items and quantities to generate a reorder list.
- A data formatter that transforms a dictionary of user attributes into a nested list for CSV export.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
When converting dictionaries to lists, a few common mistakes can lead to unexpected results and bugs in your code.
Misunderstanding what list(dictionary) returns
A frequent mistake is assuming that list(my_dict) will give you everything in the dictionary. Newcomers often expect it to return values or key-value pairs, but it only grabs the keys by default.
- This happens because iterating over a dictionary directly processes its keys, and the
list()constructor simply collects those items.
If your code then tries to perform calculations or operations expecting values, you'll run into errors because you're working with a list of keys instead.
Trying to calculate with keys instead of values
This misunderstanding often leads to another error: attempting calculations on the wrong data. For example, if you try to sum a list of string keys, Python will raise a TypeError because you can't add strings and numbers together in that way.
- To perform mathematical operations, you must explicitly extract the values using the
.values()method before converting to a list.
Losing key-value relationships when creating separate lists
Another challenge arises when you separate keys and values into two different lists. While it might seem logical, you lose the inherent connection between them. If you sort the list of keys, the list of values remains unchanged, breaking the original pairings.
- To keep each key tied to its value, it's always better to use the
.items()method. This creates a list of tuples, ensuring the key-value pairs stay together no matter how you manipulate the list.
Misunderstanding what list(dictionary) returns
It's easy to forget that calling list() on a dictionary only returns its keys, not the values or the full key-value pairs. This common oversight can lead to unexpected behavior when you try accessing data, as the following code demonstrates.
user_data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Expecting to get both keys and values
data_list = list(user_data)
print(f"Name: {data_list[0]}, Age: {data_list[1]}") # Will print keys, not values
The code attempts to access user details by indexing the list. Since list(user_data) only captures keys, the output incorrectly prints the keys 'name' and 'age' instead of their values. See the corrected approach below.
user_data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Convert to list of tuples for both keys and values
data_list = list(user_data.items())
print(f"Name: {data_list[0][1]}, Age: {data_list[1][1]}") # Access values correctly
The corrected code uses user_data.items() to create a list of key-value tuples, keeping each key paired with its value. This is the right approach when you need both pieces of data. To get a value, you index the list to select the tuple, then index the tuple for the value, like data_list[0][1]. Always use .items() when the relationship between keys and values is important for your next steps.
Trying to calculate with keys instead of values
It's easy to accidentally perform calculations on keys instead of values. When the keys are strings, Python will raise a TypeError because you can't add them numerically. The following code shows what happens when you try this with sum().
product_prices = {'apple': 1.20, 'banana': 0.50, 'orange': 0.75}
product_list = list(product_prices)
# Attempting to calculate with keys instead of values
total = sum(product_list) # TypeError: unsupported operand type(s) for +
print(f"Total price: ${total:.2f}")
The code attempts to add string keys like 'apple' and 'banana' using sum(), which causes a TypeError. You can't perform math on non-numeric text. The example below shows the correct way to get the total.
product_prices = {'apple': 1.20, 'banana': 0.50, 'orange': 0.75}
# Correctly sum the values
total = sum(product_prices.values())
print(f"Total price: ${total:.2f}")
The corrected code avoids the TypeError by calling product_prices.values(). This method isolates the numerical prices, giving the sum() function a list of numbers to add instead of non-numeric string keys.
- To perform calculations, always explicitly extract numerical data using the
.values()method.
This is a common pitfall when working with dictionaries containing price or count data, so it's a good habit to build.
Losing key-value relationships when creating separate lists
Using .keys() and .values() to create separate lists is a common pattern, but it's risky. The two lists aren't linked, so sorting one won't reorder the other. This breaks the key-value pairing and can lead to mismatched data, as the code below demonstrates.
scores = {'Alice': 95, 'Bob': 87, 'Charlie': 92}
names = list(scores.keys())
points = list(scores.values())
# Trying to match top score with student name
max_score = max(points)
top_student_index = points.index(max_score)
print(f"Top student: {names[top_student_index]}") # Breaks if order changes
This code finds the index of the max_score in the points list and uses it to retrieve a name from the names list. This approach is fragile because the two lists are completely independent. The following code shows a more reliable way to do this.
scores = {'Alice': 95, 'Bob': 87, 'Charlie': 92}
# Keep key-value relationship intact
items_list = list(scores.items())
top_scorer = max(items_list, key=lambda x: x[1])
print(f"Top student: {top_scorer[0]} with {top_scorer[1]} points")
The corrected code uses scores.items() to create a list of tuples, which keeps each name and score securely paired. It then finds the top scorer by using max() with a lambda function. The lambda tells max() to evaluate each tuple based on its second element—the score.
- This approach is much more reliable because the key-value relationship is never broken. It's essential whenever you need to sort or filter data while keeping pairs intact.
Real-world applications
Now that you can sidestep common pitfalls, you can apply these conversion methods to practical tasks like sorting data and analyzing text.
Sorting dictionary data by values()
To sort a dictionary by its values while keeping the keys attached, you can convert the items to a list and then use the sorted() function with a lambda to specify the value as the sort key.
student_scores = {'Alice': 92, 'Bob': 85, 'Charlie': 97, 'Diana': 78}
sorted_students = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
for student, score in sorted_students:
print(f"{student}: {score}")
This snippet ranks students by their scores in descending order. It’s a common pattern for creating leaderboards or ordered lists from dictionary data.
- The
sorted()function processes a list of (name, score) tuples created bystudent_scores.items(). - The
key=lambda x: x[1]argument is crucial. It tellssorted()to use the second element of each tuple—the score—as the basis for sorting. - Setting
reverse=Truearranges the list from highest to lowest score before the loop prints the final ranked results.
Using items() for text analysis with word frequencies
The dict.items() method is also perfect for text analysis, as it lets you convert a dictionary of word counts into a sortable list to find the most frequent terms.
text = "the quick brown fox jumps over the lazy dog the fox was quick"
word_freq = {}
for word in text.lower().split():
word_freq[word] = word_freq.get(word, 0) + 1
common_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:3]
print("Most common words:")
for word, count in common_words:
print(f"'{word}' appears {count} times")
This code tallies word frequencies in a string. It loops through each word, using the .get() method to increment a word's count in the word_freq dictionary. If a word isn't in the dictionary yet, .get() provides a default of 0, preventing an error.
- After counting, it converts the dictionary to a list of (word, count) tuples using
.items(). - The
sorted()function then arranges this list in descending order based on the count, which is specified by thelambdafunction. - Finally, the
[:3]slice selects the top three results.
Get started with Replit
Put these techniques into practice by building a tool with Replit Agent. Describe what you want, like “a tool to rank word frequencies from a text file” or “an app that sorts a product inventory by price”.
Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)
.png)
.png)