Python | Converting types of dictionary elements



Method # 1: Using a loop
This problem can be solved naively with loops. In this we will loop for each key and value, then typecast the keys and values ​​separately and return the desired integer container.

# Python3 code to demonstrate how it works
# Type of dictionary element conversion
# Using a loop

 
# Initialize dictionary

test_dict = { `1` : [ `4` , ` 5` ], `4` : [ `6` , ` 7` < code class = "plain">], `10` : [ `8` ]}

  
# print the original dictionary

print ( " The original dictionary: " +   str (test_dict))

 
# Using a loop
# Conversion type for dictionary elements

res = {}

for key, value in test_dict.items ():

res [ int (key)] = [ int (item) for item in value]

 
# print result

print ( "Dictionary after type conversion:" + str (res))

Output:

The original dictionary: {`10`: [`8`], `4`: [`6`, `7`] , `1`: [`4`, `5`]}
Dictionary after type conversion: {1: [4, 5], 10: [8], 4: [6, 7]}

Method # 2: Using vocabulary comprehension
This task is Can be easily accomplished using a one-line abbreviation using vocabulary comprehension. This offers a shorter alternative to the looping method discussed above and therefore recommended.

# Python3 code to demonstrate how it works
# Type of dictionary element conversion
# Using dictionary understanding

  
# Initialize dictionary

test_dict = { ` 1` : [ `4` , ` 5` ], `4` : [ ` 6` , `7` ], `10` : [ ` 8` ]}

 
# print the original dictionary

print ( "The original dictionary:" +   str (test_dict))

 
# Using dictionary comprehension
# Conversion type for dictionary elements

res = { int (key): [ int (i) for i in val]

  for key, val in test_dict.items ()}

 
# print result

print ( "Dictionary after type conversion:" + str (res))

Output:

The original dictionary: {`10`: [`8`], `4`: [ `6`, `7`], `1`: [`4`, `5`]}
Dictionary after type conversion: {1: [4, 5], 10: [8], 4: [ 6, 7]}