Converting a dictionary to a tuple allows you to represent the key-value pairs as immutable elements. In this blog post, we will explore different methods to convert a dictionary to a tuple in Python.
Method 1: Using the items() method
# Method 1: Using the items() method my_dict = {"a": 1, "b": 2, "c": 3, "d": 2} tuple_representation = tuple(my_dict.items()) print("Tuple Representation:", tuple_representation)
Output:
Tuple Representation: ((‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 2))
Method 2: Using a list comprehension and the zip() function
# Method 2: Using a list comprehension and the zip() function my_dict = {"a": 1, "b": 2, "c": 3, "d": 2} tuple_representation = list(zip(my_dict.keys(), my_dict.values())) print("Tuple Representation:", tuple_representation)
Output:
Tuple Representation: [(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 2)]