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
Python – Assign Alphabet to each element
When working with integer lists, you may need to assign alphabet letters to each element based on their sorted order. Python's string.ascii_lowercase module provides lowercase letters, and we can map them to unique values using list comprehension.
Syntax
import string string.ascii_lowercase[index] # Returns letter at given index
Example
Below is a demonstration that assigns alphabets to unique elements based on their sorted order ?
import string
my_list = [11, 51, 32, 45, 21, 66, 12, 58, 90, 0]
print("The list is:")
print(my_list)
print("The list after sorting is:")
my_list.sort()
print(my_list)
temp_val = {}
my_counter = 0
for element in my_list:
if element in temp_val:
continue
temp_val[element] = string.ascii_lowercase[my_counter]
my_counter += 1
my_result = [temp_val.get(element) for element in my_list]
print("The resultant list is:")
print(my_result)
The list is: [11, 51, 32, 45, 21, 66, 12, 58, 90, 0] The list after sorting is: [0, 11, 12, 21, 32, 45, 51, 58, 66, 90] The resultant list is: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
How It Works
Import the
stringmodule to accessascii_lowercaseSort the list to establish alphabetical assignment order
Create a dictionary to map unique numbers to letters
Iterate through sorted list, skipping duplicates with
continueAssign letters using
string.ascii_lowercase[counter]Use list comprehension with
get()to build final result
Alternative Using enumerate()
A more concise approach using enumerate() on unique sorted values ?
import string
numbers = [11, 51, 32, 45, 21, 66, 12, 58, 90, 0]
unique_sorted = sorted(set(numbers))
# Create mapping dictionary
alphabet_map = {num: string.ascii_lowercase[i] for i, num in enumerate(unique_sorted)}
# Apply mapping to original list
result = [alphabet_map[num] for num in numbers]
print("Original:", numbers)
print("Result:", result)
Original: [11, 51, 32, 45, 21, 66, 12, 58, 90, 0] Result: ['b', 'i', 'e', 'f', 'd', 'j', 'c', 'h', 'g', 'a']
Conclusion
Use string.ascii_lowercase with dictionary mapping to assign alphabet letters to list elements. Sort first to establish consistent letter assignment order based on numeric values.
