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,480
  • 3
  • 9
  • 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,525
  • 2
  • 10
  • 26
0
string = "wednesday"
dic = dict()
for character in string:
  dic[character] = dic.get(character, 0) + 1
print (dic)
kesarling He-Him
  • 1,793
  • 3
  • 10
  • 32
-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
  • 640
  • 6
  • 20