DEV Community

Flávia Bastos
Flávia Bastos

Posted on • Originally published at flaviabastos.ca on

2 1

Map a string in Python with enumerate

Problem: create a map of the letters and indices in a string.

My first approach was to loop over the string using range(len(s)), and checking if the letter exists in the map before adding it:

    s = 'mozzarella'
    mapped_s = {}
    for i in range(len(s)):
        if s[i] in mapped_s:
            mapped_s[s[i]].append(i)
        else:
            mapped_s[s[i]] = [i]
    print(f' mapped: {mapped_s}')

That works:

{'m': [0], 'o': [1], 'z': [2, 3], 'a': [4, 9], 'r': [5], 'e': [6], 'l': [7, 8]}

but there’s a more pythonic way of getting this map: use enumerate()!


    letters = 'mozzarella'
    mapped_s = collections.defaultdict(list)
    for index, letter in enumerate(letters):
        mapped_s[letter].append(index)
    print(f'mapped: {dict(mapped_s)}')

Enumerate is a python built-in function that gives you a list of tuples of the indices and the elements in an iterable:


print(f'enum {list(enumerate('mozzarella'))}')
enum [(0, 'm'), (1, 'o'), (2, 'z'), (3, 'z'), (4, 'a'), (5, 'r'), (6, 'e'), (7, 'l'), (8, 'l'), (9, 'a')]

It can be used to loop over the iterable while keeping track of the index and the element similar to what _range(len(s)) _was doing in my first example:


    for i, element in enumerate('mozzarella'):
        print(f'{i}: {element}')

It also removes the need to check if the letter already exists before creating that letter’s map!

You can read more about enumerate in the docs or this super nice article by Dan Bader.

The post Map a string in Python with enumerate was originally published on flaviabastos.ca

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Image of Datadog

Measure and Advance Your DevSecOps Maturity

In this white paper, we lay out a DevSecOps maturity model based on our experience helping thousands of organizations advance their DevSecOps practices. Learn the key competencies and practices across four distinct levels of maturity.

Get The White Paper