How we can create a dictionary from a given tuple in Python?

PythonServer Side ProgrammingProgramming

We can use zip() function to produce an iterable from two tuple objects, each corresponding to key and value items and then use dict() function to form dictionary object

>>> T1=('a','b','c','d')
>>> T2=(1,2,3,4)
>>> dict((x,y) for x,y in zip(t1,t2))

Dictionary comprehension syntax can also be used to construct dictionary object from two tuples

>>> d={k:v for (k,v) in zip(T1,T2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Updated on 25-Feb-2020 11:14:12