How to convert a dictionary to a list of tuples in Python
How to convert a dictionary to a list of tuples in Python.
Here's a step-by-step tutorial on how to convert a dictionary to a list of tuples in Python.
Step 1: Create a dictionary
Start by creating a dictionary in Python. A dictionary consists of key-value pairs enclosed in curly braces {}. Here's an example:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
Step 2: Use the items() method
To convert the dictionary to a list of tuples, you can use the items() method. This method returns a view object that contains the key-value pairs of the dictionary as tuples. Here's how you can use it:
my_list = my_dict.items()
Step 3: Convert the view object to a list
The items() method returns a view object, which you can directly use in your code. However, if you specifically need a list, you can convert the view object to a list using the list() function. Here's an example:
my_list = list(my_dict.items())
Step 4: Print the list of tuples
You can now print the list of tuples to see the result. Here's an example:
print(my_list)
The output will be:
[('apple', 3), ('banana', 5), ('orange', 2)]
Alternative method: If you prefer a one-liner solution, you can use list comprehension to achieve the same result. Here's an example:
my_list = [(key, value) for key, value in my_dict.items()]
This will give you the same output as before:
[('apple', 3), ('banana', 5), ('orange', 2)]
That's it! You have successfully converted a dictionary to a list of tuples in Python. Feel free to use this approach whenever you need to work with dictionaries and lists.