In this python dictionary program, we will convert string values of a dictionary into integer/float datatypes.
Steps to solve the program
- Take two dictionaries as input and create two empty dictionaries.
- First, use for loop to iterate over keys and values of the 1st dictionaries.
- Add the keys and values to the 1st empty dictionary.
- While adding them convert the datatype of the value from a string to an integer datatype.
- Now repeat the above step for converting the datatype of the values from the 2nd dictionary from string to float.
- Add them to the 2nd empty dictionary.
- Print the output.
A = { 'a': '30', 'b': '20', 'c': '10' }
D1 = {}
for k,v in A.items():
D1[k] = int(v)
B = { 'a': '3.33', 'b': '20.50', 'c': '12.5' }
D2 = {}
for key,val in B.items():
D2[key] = float(val)
print(D1)
print(D2)
Output :
{'a': 30, 'b': 20, 'c': 10}
{'a': 3.33, 'b': 20.5, 'c': 12.5}