In this Python Tutorial we are going to learn how to convert a type of data structure to another type.
String to Tuple:
1 2 3 4 | 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:
1 2 | convertedSet = set(s) print("Converted of set:", convertedSet) |
Converted of set: {'h', 't', 'y', 'n', 'P', 'o'}
String to List:
1 2 | 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:
1 2 3 4 | 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:
1 2 | d = dict(listing) print(d) |
{1: 2, 3: 4, 'a': ['er', 345]}
Convert a single dimensional List to Dict:
1 2 3 4 | 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