﻿ Python: Convert string values of a given dictionary, into integer/float datatypes - w3resource # Python: Convert string values of a given dictionary, into integer/float datatypes

## Python dictionary: Exercise-49 with Solution

Write a Python program to convert string values of a given dictionary, into integer/float datatypes.

Sample Solution:

Python Code:

``````def convert_to_int(lst):
result = [dict([a, int(x)] for a, x in b.items()) for b in lst]
return result

def convert_to_float(lst):
result = [dict([a, float(x)] for a, x in b.items()) for b in lst]
return result

nums =[{ 'x':'10' , 'y':'20' , 'z':'30' }, { 'p':'40', 'q':'50', 'r':'60'}]
print("Original list:")
print(nums)
print("\nString values of a given dictionary, into integer types:")
print(convert_to_int(nums))
nums =[{ 'x':'10.12', 'y':'20.23', 'z':'30'}, { 'p':'40.00', 'q':'50.19', 'r':'60.99'}]
print("\nOriginal list:")
print(nums)
print("\nString values of a given dictionary, into float types:")
print(convert_to_float(nums))
```
```

Sample Output:

```Original list:
[{'x': '10', 'y': '20', 'z': '30'}, {'p': '40', 'q': '50', 'r': '60'}]

String values of a given dictionary, into integer types:
[{'x': 10, 'y': 20, 'z': 30}, {'p': 40, 'q': 50, 'r': 60}]

Original list:
[{'x': '10.12', 'y': '20.23', 'z': '30'}, {'p': '40.00', 'q': '50.19', 'r': '60.99'}]

String values of a given dictionary, into float types:
[{'x': 10.12, 'y': 20.23, 'z': 30.0}, {'p': 40.0, 'q': 50.19, 'r': 60.99}]
```

Pictorial Presentation: Flowchart: ## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Free up Memory:

• Manual garbage collection can be performed on timely or event based mechanism.
```import gc
collected_objects = gc.collect()
```