Sometimes, while working with Python records, we can have a problem in which we need to convert each element of tuple records into a separate key in dictionary, with each index having a different value. This kind of problem can have applications in data domains. Let us discuss certain ways in which this task can be performed.
Method #1: Using loop: This is one of the ways to solve this problem. In this, we iterate for a list of tuples and assign the required value to each key for the newly constructed dictionary.
Python3
# Python3 code to demonstrate working of # Convert Records List to Segregated Dictionary # Using loop # initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # printing original list print ( "The original list is : " + str (test_list)) # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Convert Records List to Segregated Dictionary # Using loop res = dict () for sub in test_list: res[sub[ 0 ]] = frst_idx res[sub[ 1 ]] = scnd_idx # printing result print ( "The constructed Dictionary list : " + str (res)) |
The original list is : [(1, 2), (3, 4), (5, 6)] The constructed Dictionary list : {1: 'Gfg', 2: 'best', 3: 'Gfg', 4: 'best', 5: 'Gfg', 6: 'best'}
Time complexity: O(n): because it uses a loop to iterate over each element in the input list, where n is the length of the list.
Auxiliary Space: O(n): because it creates a dictionary with n key-value pairs, where n is the length of the input list. The space required by the input list and other variables used in the program is negligible in comparison.
Method #2: Using zip() + chain() + cycle() + list comprehension
The combination of the above functions can be used to perform this task. In this, we unpack the values using chain() and then alternate cycle the values to be initialized, and then zip back the values using zip() method.
Python3
# Python3 code to demonstrate working of # Convert Records List to Segregated Dictionary # Using zip() + chain() + cycle() + list comprehension from itertools import chain, cycle # initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # printing original list print ( "The original list is : " + str (test_list)) # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Convert Records List to Segregated Dictionary # Using zip() + chain() + cycle() + list comprehension res = dict ( zip (chain( * test_list), cycle([frst_idx, scnd_idx]))) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The original list is : [(1, 2), (3, 4), (5, 6)] The constructed Dictionary list : {1: 'Gfg', 2: 'best', 3: 'Gfg', 4: 'best', 5: 'Gfg', 6: 'best'}
Time complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using dictionary comprehension
This method uses dictionary comprehension to create the final dictionary. It iterates through the tuples in the test_list and uses the zip() function to combine the tuple values with the index values [frst_idx, scnd_idx]. The resulting tuples are then used to create key-value pairs in the final dictionary.
Python3
# initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Convert Records List to Segregated Dictionary # Using dictionary comprehension res = {num: idx for sub in test_list for num, idx in zip (sub, [frst_idx, scnd_idx])} # printing result print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {1: 'Gfg', 2: 'best', 3: 'Gfg', 4: 'best', 5: 'Gfg', 6: 'best'}
Time complexity of this code is O(n), where n is the length of the input list test_list, as we need to iterate through each element in the list once.
Auxiliary space complexity of this code is also O(n), as we need to store n key-value pairs in the resulting dictionary.
Method 4: Using map() function along with a lambda function.
Use map() function along with a lambda function to create two dictionaries, one for the first index value and another for the second index value. The lambda function takes a record as an argument and returns a tuple with the key-value pair. Then convert the resulting map objects into dictionaries and update the first dictionary with the second one. Finally, get the desired dictionary that is segregated by the index values.
Python3
# initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Convert Records List to Segregated Dictionary # Using map() and lambda function res = dict ( map ( lambda x: (x[ 0 ], frst_idx), test_list)) res.update( dict ( map ( lambda x: (x[ 1 ], scnd_idx), test_list))) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {1: 'Gfg', 3: 'Gfg', 5: 'Gfg', 2: 'best', 4: 'best', 6: 'best'}
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Method 5: Using setdefault() method
Uses the setdefault() method to set the value of a key in the dictionary if it doesn’t already exist. If the key already exists, the method simply returns the existing value. This allows us to avoid overwriting any values that may have been set earlier in the loop.
- Initialize an empty dictionary res.
- Loop through each tuple sub in the input list test_list.
- For each tuple, use the setdefault() method of the dictionary res to set the value of the first element of the tuple as the key in the dictionary. The value for this key will be the value of frst_idx.
- Use the setdefault() method of the dictionary res again to set the value of the second element of the tuple as the key in the dictionary. The value for this key will be the value of scnd_idx.
- Continue the loop until all tuples in test_list have been processed.
- Print the resulting dictionary res.
Python3
# Python3 code to demonstrate working of # Convert Records List to Segregated Dictionary # Using dictionary setdefault() # initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Convert Records List to Segregated Dictionary # Using dictionary setdefault() res = {} for sub in test_list: res.setdefault(sub[ 0 ], frst_idx) res.setdefault(sub[ 1 ], scnd_idx) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {1: 'Gfg', 2: 'best', 3: 'Gfg', 4: 'best', 5: 'Gfg', 6: 'best'}
Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input list test_list, because we are iterating through each element in the list only once.
Auxiliary Space:
The auxiliary space complexity of this approach is O(n), where n is the length of the input list test_list, because we are creating a dictionary that has one key-value pair for each element in the list.
Method 6 : Using the reduce() function from the functools module.
steps
Import the reduce() function from the functools module.
Define a function, say segregate_dict, that takes two parameters – a dictionary and a tuple.
For each tuple, get the first and second element and assign them to variables num and idx respectively.
Update the dictionary with the key-value pairs (num, frst_idx) and (idx, scnd_idx).
Return the updated dictionary.
Use the reduce() function to apply the segregate_dict function to each tuple in test_list.
Print the final dictionary.
Python3
from functools import reduce # initializing list test_list = [( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 )] # initializing index value frst_idx = "Gfg" scnd_idx = 'best' # Define a function to segregate dictionary def segregate_dict(dict_, tup): num, idx = tup dict_.update({num: frst_idx, idx: scnd_idx}) return dict_ # Using reduce() function to apply the function to each tuple in the list res = reduce (segregate_dict, test_list, {}) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {1: 'Gfg', 2: 'best', 3: 'Gfg', 4: 'best', 5: 'Gfg', 6: 'best'}
Time Complexity: O(n), where n is the number of tuples in test_list.
Auxiliary Space: O(n), where n is the number of tuples in test_list.