Open In App

Python – Change type of key in Dictionary list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys’ value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed.

Input : test_list = [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: ‘4’}, {‘is’: ‘2’}] 
Output : [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: 4}, {‘is’: 2}] 

Input : test_list = [{‘is’ : ‘98393’}] 
Output : [{‘is’ : 98393}]

Method #1 : Using loop This is brute force way to approach this problem. In this, we iterate for all list elements and dictionary keys and convert the desired dictionary key’s value to required type. 

Python3




# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using loop
 
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
            {'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
            {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing change key
chnge_key = 'is'
 
# Change type of key in Dictionary list
# Using loop
for sub in test_list:
        sub[chnge_key] = int(sub[chnge_key])
 
# printing result
print("The converted Dictionary list : " + str(test_list))


Output : 

The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}] The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #2 : Using list comprehension This task can also be performed using list comprehension as a shorthand. In this, we iterate for list in shorter way as above with same approach. 

Python3




# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using list comprehension
 
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
            {'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
            {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing change key
chnge_key = 'is'
 
# Change type of key in Dictionary list
# Using list comprehension
res = [{key : (int(val) if key == chnge_key else val)
                        for key, val in sub.items()}
                        for sub in test_list]
 
# printing result
print("The converted Dictionary list : " + str(res))


Output : 

The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}] The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]

Time Complexity: O(n) where n is the number of elements in the dictionary. The list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary.

Method 3 : Using the map() function with a lambda function.

Python3




# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using map() function with lambda function
 
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
            {'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
            {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
 
# printing original list
print("The original list is: ", test_list)
 
# initializing change key
chnge_key = 'is'
 
# Change type of key in Dictionary list
# Using map() function with lambda function
res = list(map(lambda x: {chnge_key: int(x[chnge_key]) if x.get(chnge_key) else x[chnge_key],
                          **{key: val for key, val in x.items() if key != chnge_key}}, test_list))
 
# printing result
print("The converted Dictionary list: ", res)


Output

The original list is:  [{'gfg': 1, 'is': '56', 'best': (1, 2)}, {'gfg': 5, 'is': '12', 'best': (6, 2)}, {'gfg': 3, 'is': '789', 'best': (7, 2)}]
The converted Dictionary list:  [{'is': 56, 'gfg': 1, 'best': (1, 2)}, {'is': 12, 'gfg': 5, 'best': (6, 2)}, {'is': 789, 'gfg': 3, 'best': (7, 2)}]

Time complexity: O(NK), where N is the number of dictionaries in the list and K is the average number of keys in each dictionary.
Auxiliary space: O(NK), as we create a new dictionary for each dictionary in the list, and each dictionary may have K keys.

Method 4 : Using the pandas library

  • Install the pandas library by running the command pip install pandas in your terminal or command prompt.
  • Import the pandas library by adding import pandas as pd at the top of your code.
  • Convert the list of dictionaries to a pandas DataFrame by calling the pd.DataFrame() function and passing in the list as an argument. This will create a DataFrame with the same keys and values as the dictionaries in the original list.
  • Use the .astype() method on the desired column of the DataFrame to change its data type. This method takes a dictionary as an argument, where the keys are the names of the columns to be converted and the values are the data types to convert to.
  • Convert the DataFrame back to a list of dictionaries by calling the .to_dict() method on the DataFrame with the argument orient=’records’. This will create a list of dictionaries with the same keys and values as the DataFrame.

Python3




# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using the pandas library
 
# import the pandas library
import pandas as pd
 
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
            {'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
            {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
 
# printing original list
print("The original list is: ", test_list)
 
# initializing change key
chnge_key = 'is'
 
# convert list of dictionaries to a pandas DataFrame
df = pd.DataFrame(test_list)
 
# change data type of desired column using .astype()
df[chnge_key] = df[chnge_key].astype(int)
 
# convert DataFrame back to list of dictionaries
res = df.to_dict(orient='records')
 
# printing result
print("The converted Dictionary list: ", res)


Output:

The original list is:  [{'gfg': 1, 'is': '56', 'best': (1, 2)}, {'gfg': 5, 'is': '12', 'best': (6, 2)}, {'gfg': 3, 'is': '789', 'best': (7, 2)}]
The converted Dictionary list:  [{'gfg': 1, 'is': 56, 'best': (1, 2)}, {'gfg': 5, 'is': 12, 'best': (6, 2)}, {'gfg': 3, 'is': 789, 'best': (7, 2)}]

Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), where n is the number of dictionaries in the list, due to the creation of the pandas DataFrame.



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