I would like to try dict comprehension with only 'key' loop and dict method, like this:
def most_frequent(str1):
d = {}
return {k:(d.get(k,0) +1) for k in str1}
str1 = 'abacdefag'
most_frequent(str1)
this returns: {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1} which is not what I expected.
I knew I could do it easy way like this:
def most_frequent(str1):
d = {}
for k in str1:
d[k] = d.get(k,0)+1
return d
str1 = 'abacdefag'
most_frequent(str1)
and return: {'a': 3, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
but I really want to know what happened inside the comprehension. anybody can help? thanks