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:
# 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]
Watch a video course
Python - The Practical Guide
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 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
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
items_list = list(map(lambda item: list(item), my_dict.items()))
print(items_list) # Output: [['a', 1], ['b', 2], ['c', 3]]