Open In App

Python | Type conversion of dictionary items

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using loop This problem can be solved using naive method by the use of loops. In this, we loop for each key and value and then typecast keys and value’s separately and returning the desired integral container. 

Python3




# Python3 code to demonstrate working of
# Type conversion of dictionary items
# Using loop
 
# Initialize dictionary
test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']}
 
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
 
# Using loop
# Type conversion of dictionary items
res = {}
for key, value in test_dict.items():
    res[int(key)] = [int(item) for item in value]
     
# printing 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]}

Time Complexity: O(NM), where N is the number of key-value pairs in the dictionary and M is the length of the list for each value in the dictionary. 

Auxiliary Space: O(NM)

Method #2 : Using dictionary comprehension This task can be easily performed using single line shorthand using dictionary comprehension. This offers a shorter alternative to the loop method discussed above and hence recommended. 

Python3




# Python3 code to demonstrate working of
# Type conversion of dictionary items
# Using dictionary comprehension
 
# Initialize dictionary
test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']}
 
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
 
# Using dictionary comprehension
# Type conversion of dictionary items
res = {int(key):[int(i) for i in val]
       for key, val in test_dict.items()}
     
# printing 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 #3: Using map()
This task can also be performed using the map() function which allows us to map a function to each element of the iterable. This task can also be performed using the same.

Python3




# Python3 code to demonstrate working of
# Type conversion of dictionary items
# Using map
   
# Initialize dictionary
test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']}
   
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
   
# Using map()
# Type conversion of dictionary items
res = dict(map(lambda k_v:(int(k_v[0]), list(map(int, k_v[1]))), test_dict.items()))
   
# printing result
print("Dictionary after type conversion : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4 : Using  json module

Step-by-step approach 

  • The first line of code imports the json module, which is a built-in module in Python that allows for the encoding and decoding of JSON data.
  • The second line of code initializes a dictionary called test_dict with three key-value pairs. The keys are strings (‘1’, ‘4’, and ’10’) and the values are lists of strings that represent numbers (‘4’ and ‘5’ for key ‘1’, ‘6’ and ‘7’ for key ‘4’, and ‘8’ for key ’10’).
  • The third line of code uses the json.dumps() method to convert the test_dict dictionary to a JSON-formatted string. This method takes a Python object (in this case, the test_dict dictionary) and returns a string in JSON format.
  • The fourth line of code uses the json.loads() method to load the JSON-formatted string as a new dictionary called res. The parse_int and parse_float arguments are used to specify functions that should be used to convert JSON integers and floats, respectively, to Python integers and floats. In this case, the functions specified simply call the int() and float() built-in functions, respectively.
  • Finally, the last line of code prints the res dictionary, which now has the same key-value pairs as the original test_dict dictionary but with the values converted to Python integers and floats.

Python3




# Import json module
import json
 
# Initialize dictionary
test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']}
 
# Convert dictionary to JSON string
json_str = json.dumps(test_dict)
 
# Load JSON string as new dictionary, with type conversion applied
res = json.loads(json_str, parse_int=lambda x:int(x), parse_float=lambda x:float(x))
 
# Print the result
print("Dictionary after type conversion : " + str(res))


Output

Dictionary after type conversion : {'1': ['4', '5'], '4': ['6', '7'], '10': ['8']}

Time complexity: O(n)
Auxiliary space: O(n)

Method #5: Using Recursion method:

Algorithm:

  1. Define a recursive function named “convert_dict_items” that takes in a dictionary as input.
  2. Iterate through each key-value pair in the dictionary using the “items()” method.
  3. If the value is a list, convert each element in the list to an integer using a list comprehension and update the dictionary.
  4. If the value is another dictionary, call the same function recursively on that dictionary.
  5. Return the updated dictionary.
  6. Initialize a dictionary named “test_dict”.
  7. Print the original dictionary.
  8. Call the “convert_dict_items” function on the “test_dict” dictionary and store the result in a variable named “res”.
  9. Print the resulting dictionary.

Python3




# Define recursive function to convert dictionary items
def convert_dict_items(d):
    for k, v in d.items():
        if isinstance(v, list):
            d[k] = [int(x) for x in v]
        elif isinstance(v, dict):
            convert_dict_items(v)
    return d
 
# Initialize dictionary
test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']}
 
# Print the original dictionary
print("The original dictionary : " + str(test_dict))
 
# Convert dictionary items recursively
res = convert_dict_items(test_dict)
 
# Print the result
print("Dictionary after type conversion : " + str(res))
#This code is contributed by Pinjala Jyothi.


Output

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

Time complexity:  O(n), where n is the number of key-value pairs in the dictionary. This is because the function visits each key-value pair once.

Auxiliary Space: O(d), where d is the maximum depth of nested dictionaries in the input dictionary. This is because the function creates a new dictionary at each level of recursion, and therefore the maximum number of dictionaries in memory at any given time is the maximum depth of nested dictionaries.



Last Updated : 17 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads