1
my_str = 'wednesday'

Output should be

d = {'w':1,'e':2,'d':2,'n':1,'s':1,'y':1,'a':1}

Is there any direct inbuilt function?

Svetlana Levinsohn
  • 1,550
  • 3
  • 10
  • 19

3 Answers3

7
>>> import collections
>>> s = 'wednesday'
>>> collections.Counter(s)
Counter({'e': 2, 'd': 2, 'w': 1, 'n': 1, 's': 1, 'a': 1, 'y': 1})
adrtam
  • 6,991
  • 2
  • 12
  • 27
0
string = "wednesday"
dic = dict()
for character in string:
  dic[character] = dic.get(character, 0) + 1
print (dic)
kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
-2

You can use the dictionary comprehension, as explained in this answer : Python Dictionary Comprehension

my_str = 'wednesday'
d = { ch:(my_str.count(ch)) for ch in my_str }
print(d)
planben
  • 680
  • 6
  • 20