![]() |
VOOZH | about |
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys.
Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4
Output : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}
Explanation : Tuples indexed starting key count from 4.Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 6
Output : {6: (4, 5), 7: (1, 3), 8: (9, 4), 9: (8, 2), 10: (10, 1)}
Explanation : Tuples indexed starting key count from 6.
Method 1 : Using loop
In this, we construct the dictionary by iterating through each tuple and adding its position index, starting from start, as key-value pair in the dictionary.
The original list is : [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
Constructed dictionary : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2 : Using dict() and enumerate()
In this, we convert tuple list to dictionary using dict(), and indexing is provided using enumerate().
The original list is : [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
Constructed dictionary : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}Time Complexity: O(n)
Auxiliary Space: O(n)
test_list: a list of tuples
start: the starting index to use for the keys in the resulting dictionary
The function uses the zip function and the itertools.count function to create a dictionary where the keys start at start and increase by 1 for each tuple in test_list, and the values are the tuples themselves.
{4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}
{6: (4, 5), 7: (1, 3), 8: (9, 4), 9: (8, 2), 10: (10, 1)}Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using a list comprehension with zip()
The original list is: [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
Constructed dictionary: {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}Time Complexity: O(n)
Auxiliary Space: O(n)