Computer >> Computer tutorials >  >> Programming >> Python

How I can convert a Python Tuple into Dictionary?


A dictionary object can be constructed using dict() function. This function takes a tuple of tuples as argument. Each tuple contains key value pair.

>>> t=((1,'a'), (2,'b'))
>>> dict(t)
{1: 'a', 2: 'b'}

If you want to interchange key and value,

>>> t=((1,'a'), (2,'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}