Check order of character in string using OrderedDict( ) in Python

When checking if characters in a string appear in the same order as a given pattern, the OrderedDict from Python's collections module provides an effective solution. This method preserves the order of characters as they first appear in the string.

How OrderedDict Helps

An OrderedDict maintains the insertion order of keys. Using OrderedDict.fromkeys() creates a dictionary with unique characters from the string in their first appearance order, which we can then compare against our pattern.

Example

from collections import OrderedDict

def check_order(my_input, my_pattern):
    my_dict = OrderedDict.fromkeys(my_input)
    pattern_length = 0
    
    for key, value in my_dict.items():
        if (key == my_pattern[pattern_length]):
            pattern_length = pattern_length + 1
        
        if (pattern_length == (len(my_pattern))):
            return 'The order of pattern is correct'
    
    return 'The order of pattern is incorrect'

my_input = 'Hi Mark'
input_pattern = 'Ma'
print("The string is:")
print(my_input)
print("The input pattern is:")
print(input_pattern)
print(check_order(my_input, input_pattern))
The string is:
Hi Mark
The input pattern is:
Ma
The order of pattern is correct

How It Works

The function creates an OrderedDict from the input string, which maintains unique characters in their order of first appearance. It then iterates through these characters, checking if they match the pattern sequence. When all pattern characters are found in order, it returns success.

Testing Different Cases

from collections import OrderedDict

def check_order(my_input, my_pattern):
    my_dict = OrderedDict.fromkeys(my_input)
    pattern_length = 0
    
    for key, value in my_dict.items():
        if (key == my_pattern[pattern_length]):
            pattern_length = pattern_length + 1
        
        if (pattern_length == (len(my_pattern))):
            return 'The order of pattern is correct'
    
    return 'The order of pattern is incorrect'

# Test cases
test_cases = [
    ('programming', 'ram'),  # Correct order
    ('programming', 'mar'),  # Incorrect order
    ('python', 'ton'),       # Correct order
    ('hello', 'ole')         # Incorrect order
]

for string, pattern in test_cases:
    result = check_order(string, pattern)
    print(f"String: '{string}', Pattern: '{pattern}' ? {result}")
String: 'programming', Pattern: 'ram' ? The order of pattern is correct
String: 'programming', Pattern: 'mar' ? The order of pattern is incorrect
String: 'python', Pattern: 'ton' ? The order of pattern is correct
String: 'hello', Pattern: 'ole' ? The order of pattern is incorrect

Key Points

  • OrderedDict.fromkeys() creates a dictionary with unique characters in order of first appearance

  • The algorithm tracks pattern position and matches characters sequentially

  • Returns success when all pattern characters are found in correct order

  • Handles duplicate characters by considering only first occurrences

Conclusion

Using OrderedDict provides an elegant way to check character order in strings by preserving the sequence of first appearances. This approach efficiently handles pattern matching while ignoring character duplicates.

Updated on: 2026-03-25T19:15:22+05:30

785 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements