0

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

Kurt
  • 1
  • 1
  • 2
    You define `d` as an empty dictionary. So within the dictionary comprehension `d.get(k, 0)` always returns `0`. – jpp Mar 20 '18 at 01:56
  • also, try `from collections import Counter; Counter(str1)`. – jpp Mar 20 '18 at 01:57
  • or `collections.defaultdict(int)` if you really want to fill in your dict yourself – Julien Mar 20 '18 at 01:57
  • If you really want to know what happens inside the comprehension, I can explain that to you, although you'll need a bit of familiarity with CPython bytecode first. But it's not going to help you with this problem. – abarnert Mar 20 '18 at 02:17
  • my question is 'can you only use key (or value) to implement dict comprehension like the one I given: {k:(d.get(k,0) +1) for k in str1} instead of using both key and value ,eg. {f(k) : f(v) for k,v in str1} – Kurt Mar 21 '18 at 12:21

0 Answers0