Python - Change type of key in Dictionary list
Last Updated :
16 May, 2023
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)
OutputThe 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.
Similar Reads
Python | Ways to change keys in dictionary Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example:Pythond = {'nikhil': 1, 'manjeet': 10, 'Amit': 15} val = d.pop('Amit') d['Suraj'] = val print(d)Output{'nikhil': 1, 'manjeet': 10, 'Suraj': 15} Explanation:T
2 min read
Dictionary keys as a list in Python In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this.Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
2 min read
Python | Type conversion of dictionary items 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 way
6 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Convert a Dictionary to a List in Python In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict
3 min read