Python | Type conversion in dictionary values



Method # 1: The Naive Method
In the naive method, we use 2 loops nested. One for all dictionaries in the list, and the second — for dictionary key-value pairs in a specific dictionary.

# Python3 demo code
# Type of conversion to a list of dictation.
# using the naive method

 
# initializing the dictionary list

test_list = [{ `a` : ` 1` , `b` : `2` }, { ` c` : `3` , ` d` : `4` }]

  
# print original list

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

 
# using naive method
# Conversation type in the dict list.

for dicts in test_list:

  for keys in dicts:

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

 
# print result

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

Output:

 The original list is: [{`a`:` 1`, `b`:` 2`}, { `c`:` 3`, `d`:` 4`}] The modified list is: [{`a`: 1,` b`: 2}, {`c`: 3,` d`: 4 }] 

Method # 2: Using items () + list comprehension
This can be easily done using just one string using a list comprehension. The items function can be used to retrieve the list values ​​when needed, and the list comprehension part handles the iteration part.

# Python3 demo code
# Type of conversion to dict list.
# use of () elements + list comprehension

 
# initializing the dictionary list

test_list = [{ `a` : `1` , ` b` : `2` }, { `c` : `3` , ` d` : `4` }]

  
# print original list

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

 
# use of () elements + list comprehension
# Type of conversation in the dict list.

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

  for key, value in dicts. items ()) 

for dicts in test_list]

  
# print result

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

Output:

 The original list is: [{`b`:` 2`, `a`:` 1`}, {`c`:` 3`, `d `:` 4`}] The modified converted list is: [{`a`: 1,` b`: 2}, {`c`: 3,` d`: 4}]