DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
FlΓ‘via Bastos
FlΓ‘via Bastos

Posted on • Originally published at flaviabastos.ca on

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

Top comments (0)

About Real-time

Join DEV and MongoDB to build a front-end application using MongoDB Atlas. Change streams to display live updates as your database changes for your entry in the DEV x MongoDB Atlas Hackathon 2022.

β†’ Join the Hackathon