0

Is there a one liner code for converting the following list/string to map, basically counting all chars and storing in map.

lst = 'leet'

map ={'l':1,'e':2,'t':1}

what i did so far

for i in lst:
    if i not in map:
        map[i] = 1
    else:
        map[i]+=1
0

3 Answers 3

2

Try

>>> from collections import Counter
>>> Counter("leet")
Counter({'e': 2, 'l': 1, 't': 1})

Source: https://realpython.com/python-counter/

Sign up to request clarification or add additional context in comments.

Comments

1

from collections import Counter; c = Counter(lst) since you said must be one-liner :)

Comments

0

{letter: "leet".count(letter) for letter in "leet"} might work

1 Comment

it does, but the str.count is a little bit inefficient when a letter is repeated multiple times in a str. also the list() constructor can be removed in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.