Skip to content

Dictionary to tuple Python

  • by

To convert a dictionary to a tuple in Python, you can use the items() method of the dictionary, which returns a list of tuples, each containing a key-value pair from the dictionary. Here’s an example:

# Sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Convert dictionary to tuple
my_tuple = tuple(my_dict.items())

print(my_tuple)

Output: ((‘a’, 1), (‘b’, 2), (‘c’, 3))

In the resulting tuple, each element is a tuple containing a key-value pair from the original dictionary. The order of elements in the tuple is determined by the order of insertion of key-value pairs in the dictionary.

Convert Dictionary to tuple Python example

Let’s demonstrate how to convert a dictionary to a tuple using each of the methods you mentioned: List function, List Comprehension, Zip function, and a For Loop.

# Sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Method 1: Using the items() method and tuple() function
tuple_method = tuple(my_dict.items())

# Method 2: Using List Comprehension
list_comprehension_method = [(key, value) for key, value in my_dict.items()]

# Method 3: Using the zip() function
zip_method = tuple(zip(my_dict.keys(), my_dict.values()))

# Method 4: Using a for loop
for_loop_method = []
for key, value in my_dict.items():
    for_loop_method.append((key, value))

# Printing the results
print("Original Dictionary:", my_dict)
print("Using items() and tuple():", tuple_method)
print("Using List Comprehension:", list_comprehension_method)
print("Using zip() function:", zip_method)
print("Using for loop:", for_loop_method)

Output:

Dictionary to tuple Python

All methods produce the same output, which is a tuple containing key-value pairs from the original dictionary. You can use any of these methods depending on your specific use case and coding preferences.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading