Python – Storing Elements Greater than K as Dictionary
Sometimes, while working with python lists, we can have a problem in which we need to extract elements greater than K. But sometimes, we don’t require to store duplicacy and hence store by key value pair in dictionary. To track of number position of occurrence in dictionary.
Method #1 : Using loop This is brute force way in which this task can be performed. In this, we store elements in form of dictionary by checking for elements greater than K.
Python3
test_list = [ 12 , 44 , 56 , 34 , 67 , 98 , 34 ]
print ("The original list is : " + str (test_list))
K = 50
res = dict ()
count = 1
for ele in test_list:
if ele > K:
res[count] = ele
count = count + 1
print ("The dictionary after storing elements : " + str (res))
|
Output :
The original list is : [12, 44, 56, 34, 67, 98, 34]
The dictionary after storing elements : {1: 56, 2: 67, 3: 98}
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using dictionary comprehension This is yet another way in which this task can be performed. In this, we just perform similar task in a shorted construct using dictionary comprehension and enumerate() for indexing.
Python3
test_list = [ 12 , 44 , 56 , 34 , 67 , 98 , 34 ]
print ("The original list is : " + str (test_list))
K = 50
res = {idx: ele for idx, ele in enumerate (test_list) if ele > = K}
print ("The dictionary after storing elements : " + str (res))
|
Output :
The original list is : [12, 44, 56, 34, 67, 98, 34]
The dictionary after storing elements : {2: 56, 4: 67, 5: 98}
Time Complexity: O(n), where n is the length of the dictionary
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res dictionary
Method #3 : Using filter()
This is yet another approach to perform this task, in this we just use filter() to filter out all the elements which are greater than K and then use dict() to convert the result into dictionary.
Python3
test_list = [ 12 , 44 , 56 , 34 , 67 , 98 , 34 ]
print ( "The original list is : " + str (test_list))
K = 50
res = dict ( filter ( lambda x : x[ 1 ] > = K, enumerate (test_list)))
print ( "The dictionary after storing elements : " + str (res))
|
Output
The original list is : [12, 44, 56, 34, 67, 98, 34]
The dictionary after storing elements : {2: 56, 4: 67, 5: 98}
Time complexity : O(N)
Auxiliary Space : O(N)
Last Updated :
20 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...