Tuple to Dictionary Conversion

Write a Python program to convert a tuple to a dictionary. The tuple is in the form (key, value). Return the dictionary.

Example 1:

Input: (('a', 1), ('b', 2), ('c', 3)) 
Output: {'a': 1, 'b': 2, 'c': 3}

Example 2:

Input: (('apple', 'fruit'), ('cabbage', 'vegetable'), ('cat', 'animal')) 
Output: {'apple': 'fruit', 'cabbage': 'vegetable', 'cat': 'animal'}

You can iterate through the tuple of tuples and assign the first element of each tuple as the key and the second element as the value in the dictionary.

def tuple_to_dict(t):
    return dict(t)

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!