Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Assign ids to each unique value in a Python list
When working with Python lists, you may need to assign unique IDs to each distinct value while ensuring that duplicate values receive the same ID. This is useful for data analysis, categorization, and indexing operations.
Using enumerate() and OrderedDict.fromkeys()
The enumerate() function creates a counter for each element, while OrderedDict.fromkeys() preserves the first occurrence order and eliminates duplicates ?
from collections import OrderedDict
values = ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
print("The given list:", values)
# Assigning ids to values
list_ids = [{v: k for k, v in enumerate(
OrderedDict.fromkeys(values))}
[n] for n in values]
# The result
print("The list of ids:", list_ids)
The given list: ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] The list of ids: [0, 1, 2, 0, 3, 4, 4]
How It Works
This method first creates a mapping dictionary where each unique value gets an ID based on its first appearance order, then maps each original list element to its corresponding ID.
Using defaultdict with Lambda
The defaultdict with a lambda function automatically assigns new IDs to unseen values while reusing existing IDs for duplicates ?
from collections import defaultdict
# Given List
values = ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
print("The given list:", values)
# Assigning ids to values
id_dict = defaultdict(lambda: len(id_dict))
list_ids = [id_dict[n] for n in values]
# Print ids of the dictionary
print("The list of ids:", list_ids)
The given list: ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] The list of ids: [0, 1, 2, 0, 3, 4, 4]
How It Works
Each time a new value is encountered, the lambda function len(id_dict) returns the current size of the dictionary as the new ID, ensuring sequential numbering.
Simple Dictionary Approach
A straightforward method using a regular dictionary and counter ?
values = ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
print("The given list:", values)
id_map = {}
counter = 0
list_ids = []
for item in values:
if item not in id_map:
id_map[item] = counter
counter += 1
list_ids.append(id_map[item])
print("The list of ids:", list_ids)
The given list: ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] The list of ids: [0, 1, 2, 0, 3, 4, 4]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| OrderedDict | Complex | Good | One-liner solutions |
| defaultdict | Moderate | Excellent | Memory efficiency |
| Simple dict | High | Good | Learning and debugging |
Conclusion
Use defaultdict for the most efficient solution, or the simple dictionary approach for better readability. All methods preserve the order of first occurrence when assigning IDs to unique values.
