How to create lists from Dictionary in Python

How to create lists from Dictionary in Python

Python’s dictionaries are a powerful data structure for storing and manipulating key-value pairs. One common task when working with dictionaries is to create lists from the values or keys in the dictionary. In this blog post, we will explore different ways to create lists from dictionaries in Python.

Creating a List of Values from a Dictionary

One way to create a list of values from a dictionary is to use the values() method. This method returns a view object that contains the values in the dictionary, which can be converted to a list using the list() function. For example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = list(my_dict.values())
print(my_list)

 

Another way to achieve the same result is by using a list comprehension. This is a compact and efficient way to create a new list by applying an expression to each item in an iterable. Here’s how you can create a list of values from a dictionary using a list comprehension:

my_list = [value for value in my_dict.values()]
print(my_list)

Creating a List of Keys from a Dictionary

To create a list of keys from a dictionary, you can use the keys() method, which returns a view object containing the keys in the dictionary. Here’s an example:

my_list = list(my_dict.keys())
print(my_list)

 

Alternatively, you can use a list comprehension to achieve the same result:

my_list = [key for key in my_dict.keys()]
print(my_list)

Creating a List of Key-Value Pairs from a Dictionary

To create a list of key-value pairs from a dictionary, you can use the items() method, which returns a view object containing the key-value pairs as tuples. Here’s an example:

my_list = list(my_dict.items())
print(my_list)

 

Alternatively, you can use a list comprehension to achieve the same result:

my_list = [(key, value) for key, value in my_dict.items()]
print(my_list)

Conclusion

In this blog post, we have explored different ways to create lists from dictionaries in Python, including creating a list of values, a list of keys, and a list of key-value pairs. Using the built-in values(), keys(), and items() methods, as well as list comprehensions, are all great options for creating lists from dictionaries in Python. It’s worth mentioning that for the above methods, the results order may differ based on the version of python you are using (Python 3.6+ dictionaries maintain order of items)

 

In this Learn through Codes example, you will learn: How to create lists from Dictionary in Python.

Essential Gigs