Appearance
Converting Dictionary to List? โ
In Python, you can convert a dictionary to a list of its keys or values using the keys() and values() methods, respectively. Here's an example:
Convert a dictionary to a list of its keys or values using the "keys()" and "values" methods in Python
python
# Initialize a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Convert to a list of keys
keys_list = list(my_dict.keys())
print(keys_list) # Output: ['a', 'b', 'c']
# Convert to a list of values
values_list = list(my_dict.values())
print(values_list) # Output: [1, 2, 3]
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
If you want to convert both keys and values of the dictionary to a list of tuples, you can use the items() method and pass each tuple to the list() constructor:
Convert both keys and values of the dictionary to a list of tuples using the items() method in Python
python
# Convert to a list of tuples (keys and values)
items_list = list(my_dict.items())
print(items_list) # Output: [('a', 1), ('b', 2), ('c', 3)]If you want to convert the dictionary to List of list where each list will have key and value then you can use list comprehension
Convert the dictionary to List of list where each list will have key and value then you can use list comprehension in Python
python
items_list = [[k,v] for k,v in my_dict.items()]
print(items_list) # Output: [['a', 1], ['b', 2], ['c', 3]]You can also use dict.items() method with map function
using items() method with map function
python
items_list = list(map(lambda item: list(item), my_dict.items()))
print(items_list) # Output: [['a', 1], ['b', 2], ['c', 3]]