Assign ids to each unique value in a Python list

PythonServer Side ProgrammingProgramming

While using Python dictionary we may need to identify each element of the dictionary uniquely. For that we have to assign unique IDs to each of the element in the dictionary. In this article we will see how to assign the same unique Id to an element if it is repeated in a Python dictionary.

With enumerate() and OrderedDict.fromkeys()

The enumerate function expands a given dictionary by adding a counter to each element of the dictionary. Then we apply the OrderedDict.fromkeys() which will extract the same value of the counter from the dictionary hence eliminating the duplicates values of IDs.

Example

 Live Demo

from collections import OrderedDict

Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)

# Assigning ids to values
list_ids = [{v: k for k, v in enumerate(
   OrderedDict.fromkeys(Alist))}
      [n] for n in Alist]

# The result
print("The list of ids : ",list_ids)

Output

Running the above code gives us the following result −

The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
The list of ids : [0, 1, 2, 0, 3, 4, 4]

Using OrderedDict from collections

In this method we use the defaultdict function which will assign a new key only to the new elements. Then we use the lambda function to loop through the new list of unique Ids.

Example

 Live Demo

from collections import defaultdict
# Given List
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)

# Assigning ids to values
d_dict = defaultdict(lambda: len(d_dict))
list_ids= [d_dict[n] for n in Alist]
# Print ids of the dictionary
print("The list of ids : ", list_ids)

Output

Running the above code gives us the following result −

The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
The list of ids : [0, 1, 2, 0, 3, 4, 4]
raja
Published on 09-Sep-2020 12:13:34
Advertisements