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?

2

3 Answers 3

7
>>> import collections
>>> s = 'wednesday'
>>> collections.Counter(s)
Counter({'e': 2, 'd': 2, 'w': 1, 'n': 1, 's': 1, 'a': 1, 'y': 1})
Sign up to request clarification or add additional context in comments.

Comments

0
string = "wednesday"
dic = dict()
for character in string:
  dic[character] = dic.get(character, 0) + 1
print (dic)

Comments

-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)

3 Comments

@OP This is called dictionary comprehension.
This is unecessarily quadratic time
This is O(N**2) when it can be done in O(N) trivially. Don't use .count in a loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.