Open In App

Python – Dictionary construction from front-rear key values

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, construct a dictionary using the key as first half values and values starting from last.

Input : test_list = [4, 10, 5, 3] 
Output : {4: 3, 10: 5} 
Explanation : First (4) is paired with rear (3) and so on. 
Input : test_list = [5, 3] 
Output : {5: 3} 
Explanation : First (5) is paired with rear (3).

Method #1: Using loop

 This is brute way in which this task can be performed. In this, we run a loop from the beginning and extract values from the beg-end and construct key-value mapping accordingly.

step-by-step approach :

  1. Create a list named test_list containing a few integer values. For example, test_list = [4, 6, 3, 10, 5, 3].
  2. Print the original list using the print() function and string concatenation. For example, print(“The original list : ” + str(test_list)).
  3. Initialize the length of the list to a variable named n using the len() function. Also, create an empty dictionary named res using the dict() function. For example, n = len(test_list) and res = dict().
  4. Run a loop until the middle of the list using the range() function and integer division (//) operator. The idx variable is used to represent the index value of the loop. For example, for idx in range(n // 2):.
  5. Inside the loop, map the front and rear key values of the list to the dictionary using the __setitem__() method. The test_list[idx] value is used as the key, and test_list[n – idx – 1] is used as the value. For example, res.__setitem__(test_list[idx], test_list[n – idx – 1]).
  6. Print the resulting dictionary using the print() function and string concatenation. For example, print(“The mapped dictionary : ” + str(res)).

Python3




# Python3 code to demonstrate working of
# Dictionary construction from front-rear key values
# Using loop
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
 
# initializing size and empty Dictionary
n = len(test_list)
res = dict()
 
# running loop till mid
for idx in range(n // 2):
 
    # mapping as required
    res.__setitem__(test_list[idx], test_list[n - idx - 1])
 
# printing result
print("The mapped dictionary : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The mapped dictionary : {4: 3, 6: 5, 3: 10}

Method #2 : Using zip() + dict()

This is yet another way in which this task can be performed. In this, we perform the task of zipping key and value elements using zip() and dict() is used to convert result to dictionary.

Python3




# Python3 code to demonstrate working of
# Dictionary construction from front-rear key values
# Using zip() + dict()
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# using zip to cut first and second half
n = len(test_list)
res = dict(zip(test_list[:n // 2], test_list[n // 2:][::-1]))
 
# printing result
print("The mapped dictionary : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The mapped dictionary : {4: 3, 6: 5, 3: 10}

The time complexity of the given program is O(n), where n is the length of the input list test_list.

The space complexity of the given program is O(n/2), since the zip() function creates a new list of length n/2 to store the tuples formed from the elements of the input list.

Method #3: Using a single loop and two pointers

Construct the dictionary by iterating through the list with two pointers, one pointing to the beginning and the other to the end of the list. At each iteration, you can add a new key-value pair to the dictionary with the value of the front pointer as the key and the value of the rear pointer as the value. Then, you can increment the front pointer and decrement the rear pointer until they cross each other.

Python3




test_list = [4, 6, 3, 10, 5, 3]
 
n = len(test_list)
front = 0
rear = n - 1
res = {}
 
while front <= rear:
    res[test_list[front]] = test_list[rear]
    front += 1
    rear -= 1
 
print("The mapped dictionary : " + str(res))


Output

The mapped dictionary : {4: 3, 6: 5, 3: 10}

Time complexity: O(n), where n is the length of given test_list
Auxiliary space: O(n)

Method 4: using the enumerate() function and a dictionary comprehension:

Approach:

  1. Initialize the input list test_list with the given values.
  2. Create an empty dictionary res.
  3. Use a dictionary comprehension to iterate over the first half of test_list using enumerate() function, where i is the index of the current element and _ is the placeholder for the element itself.
  4. For each iteration, add a new key-value pair to res where the key is the current element at index i and thevalue is the element at the opposite end of the list using -i-1 as the index.
  5. Print the resulting dictionary res.

Python3




test_list = [4, 6, 3, 10, 5, 3]
 
res = {test_list[i]: test_list[-i-1]
       for i, _ in enumerate(test_list[:len(test_list)//2])}
 
print("The mapped dictionary : " + str(res))


Output

The mapped dictionary : {4: 3, 6: 5, 3: 10}

Time complexity: O(n/2) since we only iterate over half of the input list.
Auxiliary space: O(n/2) since we create a dictionary with half of the size of the input list.

Method 5: Using recursion

We can also use a recursive function to construct the dictionary from front-rear key values. The function takes two arguments: the list and the length of the list. If the length of the list is 0 or 1, we return an empty dictionary. Otherwise, we construct the dictionary by recursively calling the function with the sliced list and its length minus 2.

Steps:

  1. Define a recursive function construct_dict() that takes two arguments: lst and n.
    If n is 0 or 1, return an empty dictionary {}.
  2. Otherwise, construct the dictionary by recursively calling the function with the sliced list lst[1:n-1] and its length minus 2 n-2, and merging the resulting dictionary with {lst[0]: lst[n-1]} using the unpacking operator **.
  3. Initialize the list test_list.
  4. Calculate the length of the list using the len() function.
  5. Call the construct_dict() function with test_list and n, and assign the result to res.
  6. Print the mapped dictionary.

Python3




# recursive function to construct dictionary
def construct_dict(lst, n):
    if n == 0 or n == 1:
        return {}
    else:
        return {lst[0]: lst[n-1], **construct_dict(lst[1:n-1], n-2)}
 
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# constructing dictionary using recursion
n = len(test_list)
res = construct_dict(test_list, n)
 
# printing result
print("The mapped dictionary : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The mapped dictionary : {4: 3, 6: 5, 3: 10}

Time Complexity: O(n^2)
The time complexity of the construct_dict() function is O(n^2) because the slicing operation lst[1:n-1] takes O(n) time, and the function is called recursively n/2 times. Therefore, the overall time complexity of the program is O(n^2).

Auxiliary Space: O(n)
The auxiliary space used by the program is O(n) because we need to store the dictionary that maps the front-rear key values, and the maximum size of the dictionary is n/2. The recursive function also uses O(n) stack space due to the recursive calls. Therefore, the overall auxiliary space of the program is O(n).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads