Python | Assign IDs to each unique value in the list

Python Methods and Functions

Method # 1: Using defaultdict + lambda + comprehension list

A combination of the above functions can be used to accomplish this particular task. The defaultdict function does the main job of assigning identifiers using a lambda function, assigning the current number of keys to each new key. List comprehension is used at a later stage to form the list.

# Python3 demo code
# assigning identifiers to values ​​
# using comprehension list + defaultdict + lambda

from collections import defaultdict

 
# initializing list

test_list = [ 5 , 6 , 7 , 6  , 5 , 1 ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# using comprehension list + defaultdict + lambda
# assigning identifiers to values

temp = defaultdict ( lambda : len (temp ))

res = [temp [ele] for ele in test_list]

 
# print result

print ( "The ids of assigned values ​​is: " + str (res))

Output:

 The original list: [5, 6, 7, 6, 5, 1] ​​The ids of assigned values ​​is: [0, 1, 2, 1, 0, 3] 

Method # 2: Using OrderedDict.fromkeys () + enumerate () + list comprehension

This method performs the same task as described above. In this function, orderDict.fromkeys does the duplicate removal function, and the enumeration function helps us get the indices of the values ​​to display together.

# Python3 demo code
# assigning identifiers to values ​​using
# comprehension list + OrderedDict.fromkeys () + enumerate ()

from collections import OrderedDict

 
# initializing list

test_list = [ 5 , 6 , 7 , 6 , 5 , 1 ]

 
# print original list

print ( "The original list:" + str (test_list))

  
# using comprehension list + OrderedDict.fromkeys () + enumerate ()
# assigning identifiers values ​​

res = [{val: key for key, val in   enumerate (

OrderedDict.fromkeys (test_list))}

[ele] for ele in test_list]

 
# print result

print ( "The ids of assigned values ​​is:" + str (res))

Output:

 The original list: [5, 6, 7, 6, 5, 1] ​​The ids of assigned values ​​is: [0, 1, 2, 1, 0, 3] 




Tutorials