![]() |
VOOZH | about |
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.
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.
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.
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
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:
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.