Open In App

Python | Transcribing dictionary key

Improve
Improve
Like Article
Like
Save
Share
Report

While working with data, we can come across various data interconversions that we wish to perform. These can be of transcribing a key inside a list of dictionary to the outer part for generalizations. This type of utility is quite useful to know. Let’s discuss certain ways in which this can be performed. 

Method #1 : Using dictionary comprehension This particular task can be performed using the method of dictionary comprehension in which we assign the keys and values from the desired lists and remake the dictionary. 

Python3




# Python3 code to demonstrate
# Dictionary key transcription
# dictionary comprehension
 
# initializing list
test_list = [{'state' : 'Haryana', 'capital' : 'Chandigarh', 'area' : 'North'},
             {'state' : 'Karnataka', 'capital' : 'Bengaluru', 'area' : 'South'}]
 
# printing original list
print("The original list : " + str(test_list))
 
# using Dictionary comprehension
# Dictionary key transcription
res = { sub["state"]: {"capital": sub["capital"], "area": sub["area"] }
        for sub in test_list }
 
# print result
print("The Dictionary after transcription of key : " + str(res))


Output : 

The original list : [{‘capital’: ‘Chandigarh’, ‘state’: ‘Haryana’, ‘area’: ‘North’}, {‘capital’: ‘Bengaluru’, ‘state’: ‘Karnataka’, ‘area’: ‘South’}] The Dictionary after transcription of key : {‘Haryana’: {‘capital’: ‘Chandigarh’, ‘area’: ‘North’}, ‘Karnataka’: {‘capital’: ‘Bengaluru’, ‘area’: ‘South’}}

Method #2 : Using dictionary comprehension + items() + get() This task can also be performed using a set of functions as well. This method allows the flexibility of adding any key of choice. This is useful in cases where keys are not known in advance. 

Python3




# Python3 code to demonstrate
# Dictionary key transcription
# dictionary comprehension + items() + get()
 
# initializing list
test_list = [{'state' : 'Haryana', 'capital' : 'Chandigarh', 'area' : 'North'},
             {'state' : 'Karnataka', 'capital' : 'Bengaluru', 'area' : 'South'}]
 
# printing original list
print("The original list : " + str(test_list))
 
# using dictionary comprehension + items() + get()
# Dictionary key transcription
res = {sub.get('state'): {key: val for key, val in sub.items()
        if key != 'state'} for sub in test_list}
 
# print result
print("The Dictionary after transcription of key : " + str(res))


Output : 

The original list : [{‘capital’: ‘Chandigarh’, ‘state’: ‘Haryana’, ‘area’: ‘North’}, {‘capital’: ‘Bengaluru’, ‘state’: ‘Karnataka’, ‘area’: ‘South’}] The Dictionary after transcription of key : {‘Haryana’: {‘capital’: ‘Chandigarh’, ‘area’: ‘North’}, ‘Karnataka’: {‘capital’: ‘Bengaluru’, ‘area’: ‘South’}}

Method #3: Using Map and Lambda Functions

A list of dictionaries is created using the map function with a lambda function applied to each dictionary in the original list. The lambda function creates a new dictionary with the state as the key and the ‘capital’ and ‘area’ keys and their corresponding values. Then, using a for loop, the dictionaries in the list are merged into a single dictionary using the update method. Finally, the main dictionary is returned.

Step-by-step approach:

1. Using the map function, create a list of dictionaries by applying a lambda function to each dictionary in the original list.
2. Merge the dictionaries in the list created in step 1 into a single dictionary using the update method.
3. Return the main dictionary.

Python3




def transcribe_dict_3(original_list):
    dicts = list(map(lambda d: {d['state']: {'capital': d['capital'], 'area': d['area']}}, original_list))
    main_dict = {}
    for d in dicts:
        main_dict.update(d)
    return main_dict
 
original_list = [{'state' : 'Haryana', 'capital' : 'Chandigarh', 'area' : 'North'},
             {'state' : 'Karnataka', 'capital' : 'Bengaluru', 'area' : 'South'}]
print(transcribe_dict_3(original_list)) 


Output

{'Haryana': {'capital': 'Chandigarh', 'area': 'North'}, 'Karnataka': {'capital': 'Bengaluru', 'area': 'South'}}

Time complexity: O(n), where n is the length of the original list.
Auxiliary Space: O(n), where n is the length of the original list.

Method 4: Using defaultdict module and a for loop: The given code is an implementation in Python to transcribe a list of dictionaries into a new dictionary, with the ‘state’ value from each dictionary being used as the key of the new dictionary. The ‘capital’ and ‘area’ values from each dictionary are used as the values in the new dictionary, corresponding to their respective keys. This implementation uses defaultdict and a for loop to achieve this transcription.

Step-by-step approach:

  1. Import defaultdict from the collections module
  2. Create a defaultdict with a default value of an empty dictionary
  3. Loop through each item in the original list
  4. For each item, extract the values of ‘capital’, ‘state’, and ‘area’
  5. Create a new dictionary with keys ‘capital’ and ‘area’, and values corresponding to their respective values in the original dictionary
  6. Add the new dictionary as a value to the key of the state in the defaultdict
  7. Convert the defaultdict to a regular dictionary using the dict() function
  8. Return the resulting dictionary

Python3




from collections import defaultdict
 
original_list = [{'capital': 'Chandigarh', 'state': 'Haryana', 'area': 'North'}, {
    'capital': 'Bengaluru', 'state': 'Karnataka', 'area': 'South'}]
 
new_dict = defaultdict(dict)
 
for item in original_list:
    capital = item['capital']
    state = item['state']
    area = item['area']
    new_dict[state]['capital'] = capital
    new_dict[state]['area'] = area
 
new_dict = dict(new_dict)
 
print(new_dict)


Output

{'Haryana': {'capital': 'Chandigarh', 'area': 'North'}, 'Karnataka': {'capital': 'Bengaluru', 'area': 'South'}}

Time Complexity: O(n), where n is the number of items in the original list. The for loop iterates through each item once.
Space Complexity: O(n), where n is the number of items in the original list. The defaultdict stores each item as a key-value pair. The resulting regular dictionary also stores each item as a key-value pair.

Method 5: Using numpy:

Step-by-step approach:

  1. Create an empty dictionary new_dict.
  2. Extract a list of unique states from the original list using NumPy.
  3. Iterate over each state in the unique states list.
  4. Extract all items in the original list that correspond to the current state using a list comprehension.
  5. Extract the capital and area of the first item in the state_items list and store them in new_dict with the state as the key.
  6. Output new_dict.

Python3




import numpy as np
 
original_list = [{'capital': 'Chandigarh', 'state': 'Haryana', 'area': 'North'},
                 {'capital': 'Bengaluru', 'state': 'Karnataka', 'area': 'South'}]
 
states = np.unique([item['state'] for item in original_list])
 
new_dict = {}
for state in states:
    state_items = [item for item in original_list if item['state'] == state]
    capital = state_items[0]['capital']
    area = state_items[0]['area']
    new_dict[state] = {'capital': capital, 'area': area}
 
print(new_dict)
# This code is contributed by Pushpa.


Output:

{'Haryana': {'capital': 'Chandigarh', 'area': 'North'}, 'Karnataka': {'capital': 'Bengaluru', 'area': 'South'}}

Time Complexity:
The time complexity  is O(n * log(n)), where n is the length of the original list. This is because the NumPy unique() method has a time complexity of O(n * log(n)), and the for loop iterates over each unique state in the list, which takes O(n) time in the worst case. The list comprehension inside the for loop also takes O(n) time in the worst case. Therefore, the overall time complexity is O(n * log(n)).

Space Complexity:
The space complexity  O(n), where n is the length of the original list. This is because we are creating a dictionary new_dict to store the results, which takes O(n) space in the worst case due to the number of keys and values stored in it. The unique() method also creates a NumPy array of unique states, which takes O(n) space in the worst case. Therefore, the overall space complexity is O(n).

Method 6: Using a for loop and dictionary manipulation

  • Initialize an empty dictionary named “res”.
  • Start a for loop that iterates over each dictionary in “test_list”.
  • For each dictionary in “test_list”, initialize a new dictionary named “new_dict”.
  • Start another for loop that iterates over each key-value pair in the current dictionary.
  • If the key is “state”, set the new key to the current value of “state”.
  • Otherwise, capitalize the key and set the new key to the capitalized key.
  • Add the key-value pair to “new_dict”.
  • After all key-value pairs have been added to “new_dict”, remove the key “State” from the dictionary using the pop() method.
  • Add the modified dictionary to “res” with the state name as the key.
  • Print the modified dictionary using the print() function and concatenation with a string.

Python3




# initializing list
test_list = [{'state': 'Haryana', 'capital': 'Chandigarh', 'area': 'North'},
             {'state': 'Karnataka', 'capital': 'Bengaluru', 'area': 'South'}]
 
# printing original list
print("The original list : " + str(test_list))
 
# using a for loop and dictionary manipulation
# Dictionary key transcription
res = {}
for sub in test_list:
    new_dict = {}
    for key, val in sub.items():
        new_key = key.capitalize()
        new_dict[new_key] = val
    res[new_dict.pop('State')] = new_dict
 
# print result
print("The Dictionary after transcription of key : " + str(res))


Output

The original list : [{'state': 'Haryana', 'capital': 'Chandigarh', 'area': 'North'}, {'state': 'Karnataka', 'capital': 'Bengaluru', 'area': 'South'}]
The Dictionary after transcription of key : {'Haryana': {'Capital': 'Chandigarh', 'Area': 'North'}, 'Karnataka': {'Capital': 'Bengaluru', 'Area': 'South'}}

The time complexity of this method is O(nm), where n is the number of dictionaries in test_list and m is the average number of key-value pairs in each dictionary. 

The auxiliary space complexity is O(nm) for the res and new_dict dictionaries.



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