Open In App

Python – Convert each list element to key-value pair

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given list of elements, convert each element to a key-value pair dictionary, dividing digits equally.

Input : test_list = [2323, 82, 129388, 234, 95] 
Output : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5} 
Explanation : Digits distributed equally to keys and values.

Input : test_list = [2323, 82, 129388] 
Output : {23: 23, 8: 2, 129: 388} 
Explanation : Digits distributed equally to keys and values. 
 

Approach: Using list slicing + loop

In this, we form key-value pair by getting the sliced values from each element by dividing by half the digits for keys and values.

Python3




# Python3 code to demonstrate working of
# Convert each list element to key-value pair
# Using loop + list slicing
 
# initializing list
test_list = [2323, 82, 129388, 234, 95]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dict()
for ele in test_list:
 
    # constructing key and values
    mid_idx = len(str(ele)) // 2
    key = int(str(ele)[:mid_idx])
    val = int(str(ele)[mid_idx:])
 
    # item assignment
    res[key] = val
 
# printing result
print("Constructed Dictionary : " + str(res))


Output

The original list is : [2323, 82, 129388, 234, 95]
Constructed Dictionary : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5}

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

Method 2: Using dictionary comprehension

Step-by-step approach:

  • Initialize the test_list with the given values.
  • Use dictionary comprehension to create a dictionary.
  • Iterate through the test_list and construct the key and value for each element using slicing.
  • Use int() function to convert the sliced string into integers.
  • Create a key-value pair in the dictionary using the key and value.
  • Print the original list and the constructed dictionary.

Python3




test_list = [2323, 82, 129388, 234, 95]
 
# Dictionary comprehension to create a dictionary
res = {int(str(ele)[:len(str(ele)) // 2]): int(str(ele)[len(str(ele)) // 2:]) for ele in test_list}
 
# printing original list and constructed dictionary
print("The original list is : " + str(test_list))
print("Constructed Dictionary : " + str(res))


Output

The original list is : [2323, 82, 129388, 234, 95]
Constructed Dictionary : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5}

The time complexity of the above program is O(n), where n is the length of the list. 
The auxiliary space complexity of the program is O(n), where n is the length of the list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads