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
Zeus
  • 6,386
  • 6
  • 54
  • 89

3 Answers3

2

Try

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

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

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
Jeffrey Ram
  • 1,132
  • 1
  • 10
  • 16
1

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

mj_codec
  • 170
  • 8
0

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

thebadgateway
  • 433
  • 1
  • 4
  • 7
  • 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. – rv.kvetch Aug 16 '22 at 02:40