How to convert Python tuple to dictionary

Published on Aug. 22, 2023, 12:16 p.m.

To convert a Python tuple to a dictionary, you can use the dict() function. You can pass the tuple as an argument to the dict() function, and it will return a dictionary with keys and values corresponding to the elements of the tuple. Here’s an example:

my_tuple = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(my_tuple)

print(my_dict)   # Output: {'a': 1, 'b': 2, 'c': 3}

In this example, we define a tuple my_tuple containing three tuples, each representing a key-value pair. We use the dict() function to convert the tuple into a dictionary. The resulting dictionary contains the same 3 items as the original tuple.

Note that the first element of each tuple becomes the key in the resulting dictionary, and the second element becomes the corresponding value. If there are duplicate keys in the tuple, the last value associated with that key will be retained in the dictionary.

In general, converting a tuple to a dictionary can be useful when you need to represent a collection of key-value pairs, and you want to perform dictionary operations on it like searching for a key, retrieving a value by key, or updating the key/value pairs.

Tags:

related content