Converting a dictionary to a list allows you to extract the key-value pairs and store them as separate elements. In this blog post, we will explore different methods to convert a dictionary to a list in Python.
Method 1: Converting to a List of Tuples Using the items() Method
# Method 1: Converting to a List of Tuples Using the items() Method my_dict = {"name": "John", "age": 30, "city": "New York"} list_of_tuples = list(my_dict.items()) print("List of tuples:", list_of_tuples)
Output:
List of tuples: [(‘name’, ‘John’), (‘age’, 30), (‘city’, ‘New York’)]
Method 2: Converting to a List of Keys or Values
# Method 2: Converting to a List of Keys or Values my_dict = {"name": "John", "age": 30, "city": "New York"} list_of_keys = list(my_dict.keys()) list_of_values = list(my_dict.values()) print("List of keys:", list_of_keys) print("List of values:", list_of_values)
Output:
List of keys: [‘name’, ‘age’, ‘city’]
List of values: [‘John’, 30, ‘New York’]