Python Tutorial – Data Structure Type Conversion

We can convert a type of data structure to another type. Learn to convert the type of a data structure to another type.

In this Python Tutorial we are going to learn how to convert a type of data structure to another type.

String to Tuple:

s = 'Python'
print("type of S:",type(s))
c = tuple(s)
print("Converted to tuple:",c)
type of S: <class 'str'>
Converted to tuple: ('P', 'y', 't', 'h', 'o', 'n')

String to Set:

convertedSet = set(s)
print("Converted of set:", convertedSet)
Converted of set: {'h', 't', 'y', 'n', 'P', 'o'}

String to List:

convertedList = list(s)
print("type of list:", convertedList)
type of list: ['P', 'y', 't', 'h', 'o', 'n']

Convert a List to Dict:

When we try to convert a list to dict, each element itself should be single dimensional. ie., the list should be multi-dimensional.

It is because each element will be converted to a key value pair of a dictionary.

When the entire list is single dimensional, it is not sufficient for both key and value pair. At that time the TypeError will be thrown.

Lets take a multi-dimensional list:

listing = [[1,2],[3,4],['a',['er',345]]]
print(listing[1][1])
print(listing[1][0])
print(listing[2][1][1])
4
3
345

Convert it to a dictionary:

d = dict(listing)
print(d)
{1: 2, 3: 4, 'a': ['er', 345]}

Convert a single dimensional List to Dict:

list_1d = [4.2,6,7,1] 
dict_1d = dict(list_1d)
print(dict_1d)
print(type(dict_1d))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-20c1ca8b8462> in <module>
      1 list_1d = [4.2,6,7,1]
----> 2 dict_1d = dict(list_1d)
      3 print(dict_1d)
      4 print(type(dict_1d))

TypeError: cannot convert dictionary update sequence element #0 to a sequence

Asha Ponraj
Asha Ponraj

Data science and Machine Learning enthusiast | Software Developer | Blog Writter

Articles: 86

Leave a Reply

Your email address will not be published. Required fields are marked *