Python Tutorial

What is Python Type Conversion? Explained With Example

What is Type Conversion in Python?

Traditional type conversion is a common problem that may be readily solved by using the built-in converters in Python modules. However, in a more sophisticated case, such as for keys in a list of dictionaries, we may require the same capability. 

Let's look at several options for accomplishing this.

Naive Method in Python

We use two stacked loops in the naïve technique. One is for all of the dictionaries in the list. Another is for the dictionary key-value pairs in a single dictionary.

test_list = [{'w' : '1', 'x' : '2'}, { 'y' : '3', 'z' : '4'}]

# printing real list

print ("The real list is : " + str(test_list))

# using naive method

# type conversation in list of dicts.

for dicts in test_list:

    for keys in dicts:

        dicts[keys] = int(dicts[keys])

# printing result

print ("The modified converted list is : " +  str(test_list))

Output

The real list is : [{'w': '1', 'x': '2'}, {'y': '3', 'z': '4'}]

The modified converted list is : [{'w': 1, 'x': 2}, {'y': 3, 'z': 4}]

Using items() + list Comprehension

With the assistance of list comprehension, this can be done with just one line. The items function can be used to extract list values as needed, and the iteration is handled by the list comprehension component.

Example

test_list = [{'w' : '1', 'x' : '2'}, { 'y' : '3', 'z' : '4'}]

 print ("The real list is : " + str(test_list))

res = [dict([key, int(value)]

       for key, value in dicts.items())

       for dicts in test_list]   

# printing result

print ("The modified converted list is : " +  str(res))

Output 

The real list is : [{'x': '2', 'w': '1'}, {'y': '3', 'z': '4'}]
The modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]

It’s Quiz Time!

quiz-img
Did you find this article helpful?