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 – Character indices Mapping in String List
When working with string lists, you may need to map each character to the indices where it appears. Python provides an efficient solution using defaultdict from the collections module combined with enumeration and set operations.
Syntax
from collections import defaultdict
result = defaultdict(set)
for index, string in enumerate(string_list):
for char in string.split():
result[char].add(index + 1)
Example
Below is a demonstration that maps each character to its string positions ?
from collections import defaultdict
my_list = ['p y t h o n', 'i s', 'f u n', 't o', 'l e a r n']
print("The list is :")
print(my_list)
my_result = defaultdict(set)
for index, element in enumerate(my_list):
for sub in element.split():
my_result[sub].add(index + 1)
my_result = {key: list(val) for key, val in my_result.items()}
print("The result is :")
print(my_result)
The list is :
['p y t h o n', 'i s', 'f u n', 't o', 'l e a r n']
The result is :
{'p': [1], 'y': [1], 't': [1, 4], 'h': [1], 'o': [1, 4], 'n': [1, 3, 5], 'i': [2], 's': [2], 'f': [3], 'u': [3], 'l': [5], 'e': [5], 'a': [5], 'r': [5]}
How It Works
The algorithm follows these steps:
Import defaultdict: Creates a dictionary with default set values
Enumerate strings: Gets both index and string content using
enumerate()Split characters: Uses
split()to separate space-delimited charactersMap indices: Adds each character's position (index + 1) to its corresponding set
Convert to lists: Dictionary comprehension converts sets to lists for final output
Key Points
defaultdict(set)automatically creates an empty set for new keysenumerate()provides both index and value during iterationUsing sets prevents duplicate indices for the same character
Index + 1 creates 1-based positioning instead of 0-based
Conclusion
This approach efficiently maps characters to their string positions using defaultdict and sets. The technique is particularly useful for text analysis and character frequency tracking in structured string data.
