Open In App

Python – Change type of key in Dictionary list

Last Updated : 16 May, 2023
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.



Similar Reads

Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 min read
Python - Convert list to Single Dictionary Key Value list
Sometimes, while working with Python lists, we can have a problem in which we need to convert the list into a dictionary, which has single key, the Kth element of list, and others as its list value. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [6, 5,
7 min read
Python - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with respective rest of words as list. Input : test_li
8 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
3 min read
Python | Filter dictionary key based on the values in selective list
In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is quite common in web development we require to get only the selective dictionary keys from some given list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension The list comprehension can be used to solv
9 min read
Python - Dictionary Key's Product in list
Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the product of values of key in the dictionary list. This task is common in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + list
6 min read
Practice Tags :