Convert Dictionary to List in Python
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
In Python, a dictionary stores key-value pairs. Sometimes you need to convert its keys or values into lists. This is done with the keys() and values() methods combined with the list() function.
- list(my_dict.keys()) creates a list of all keys.
- list(my_dict.values()) creates a list of all values.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
values_list = list(my_dict.values())Output:
list of keys: ['a', 'b', 'c'] list of values: [1, 2, 3]
You can also use the items() method to get both keys and values as tuples in a list.