Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Change Keys Case in Dictionary

Python – Change Keys Case in Dictionary

Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform manipulation of cases of keys. This can have possible application in many domains including school programming and data domains. Lets discuss a way to solve this task.

Input : test_dict = {‘Gfg’ : {‘a’ : 5, ‘b’ : {‘best’ : 6}}} 
Output : {‘GFG’: {‘A’: 5, ‘B’: {‘BEST’: 6}}} 

Input : test_dict = {‘Gfg’ : 6} 
Output : {‘GFG’: 6}

Method 1: Using isinstance() + upper() + recursion + loop The combination of above functions can also be used to solve this problem. In this, we use upper() to perform upper case of keys, recursion is used to perform keys manipulation in nested keys as well. The isinstance() is used to check if nesting is dictionary. 

Python3




# Python3 code to demonstrate working of
# Change Keys Case in Dictionary
# Using isinstance() + toupper() + recursion + loop
 
# helper function
def keys_upper(test_dict):
    res = dict()
    for key in test_dict.keys():
        if isinstance(test_dict[key], dict):
            res[key.upper()] = keys_upper(test_dict[key])
        else:
            res[key.upper()] = test_dict[key]
    return res
 
# initializing dictionary
test_dict = {'Gfg' : {'a' : 5, 'b' : 6}, 'is' : {'for' :2}, 'best': 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Change Keys Case in Dictionary
# Using isinstance() + toupper() + recursion + loop
res = keys_upper(test_dict)
 
# printing result
print("The modified dictionary : " + str(res))


Output : 

The original dictionary : {'is': {'for': 2}, 'Gfg': {'b': 6, 'a': 5}, 'best': 3}
The modified dictionary : {'GFG': {'A': 5, 'B': 6}, 'IS': {'FOR': 2}, 'BEST': 3}

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method 2: Using type() + upper() + recursion + loop 

Approach

The combination of above functions can also be used to solve this problem. In this, we use upper() to perform upper case of keys, recursion is used to perform keys manipulation in nested keys as well. The type() is used to check if nesting is dictionary. 

Python3




# Python3 code to demonstrate working of
# Change Keys Case in Dictionary
# Using type() + toupper() + recursion + loop
 
# helper function
def keys_upper(test_dict):
    res = dict()
    for key in test_dict.keys():
        if type(test_dict[key]) is dict:
            res[key.upper()] = keys_upper(test_dict[key])
        else:
            res[key.upper()] = test_dict[key]
    return res
 
# initializing dictionary
test_dict = {'Gfg' : {'a' : 5, 'b' : 6}, 'is' : {'for' :2}, 'best': 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Change Keys Case in Dictionary
# Using type() + toupper() + recursion + loop
res = keys_upper(test_dict)
 
# printing result
print("The modified dictionary : " + str(res))


Output

The original dictionary : {'Gfg': {'a': 5, 'b': 6}, 'is': {'for': 2}, 'best': 3}
The modified dictionary : {'GFG': {'A': 5, 'B': 6}, 'IS': {'FOR': 2}, 'BEST': 3}

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

Method 3: using dictionary comprehension and the str.upper() method:

This method uses a dictionary comprehension to create a new dictionary where all keys are converted to upper case. If a value is itself a dictionary, the function is called recursively to convert the keys in the nested dictionary as well. If the value is not a dictionary, it is left unchanged.

Python3




def keys_upper(test_dict):
    return {k.upper(): keys_upper(v) if isinstance(v, dict) else v for k, v in test_dict.items()}
 
test_dict = {'Gfg' : {'a' : 5, 'b' : 6}, 'is' : {'for' :2}, 'best': 3}
res = keys_upper(test_dict)
print(res)


Output

{'GFG': {'A': 5, 'B': 6}, 'IS': {'FOR': 2}, 'BEST': 3}

Time complexity: O(N), where N is the total number of keys in all nested dictionaries, because each key needs to be checked and potentially converted to upper case. 
Auxiliary space: O(N), because a new dictionary is created with the same number of keys as the original dictionary.

Method 5: Using map() and lambda function

Step-by-step approach:

  1. Define a function called change_keys_case() that takes a dictionary as an argument.
  2. Inside the function, create a new dictionary by mapping the keys of the original dictionary to uppercase using a lambda function.
  3. For each key-value pair in the original dictionary, check if the value is a nested dictionary. If it is, call the change_keys_case() function recursively on the nested dictionary.
  4. Return the modified dictionary.

Python3




# Python3 code to demonstrate working of
# Change Keys Case in Dictionary
# Using map() + lambda + recursion
 
# helper function
def change_keys_case(test_dict):
    # create new dictionary with uppercase keys
    new_dict = dict(map(lambda x: (x[0].upper(), x[1]), test_dict.items()))
 
    # check if values are nested dictionaries and call function recursively
    for key, value in new_dict.items():
        if isinstance(value, dict):
            new_dict[key] = change_keys_case(value)
 
    return new_dict
 
# initializing dictionary
test_dict = {'Gfg' : {'a' : 5, 'b' : 6}, 'is' : {'for' :2}, 'best': 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Change Keys Case in Dictionary
# Using map() + lambda + recursion
res = change_keys_case(test_dict)
 
# printing result
print("The modified dictionary : " + str(res))


Output

The original dictionary : {'Gfg': {'a': 5, 'b': 6}, 'is': {'for': 2}, 'best': 3}
The modified dictionary : {'GFG': {'A': 5, 'B': 6}, 'IS': {'FOR': 2}, 'BEST': 3}

The time complexity of this method is O(n), where n is the number of keys in the dictionary. 
The auxiliary space complexity is O(n) as well, as a new dictionary is created and the function is called recursively for each nested dictionary.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments