Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there dictionary comprehensions in Python? (Problem with function returning dict)

I know about list comprehensions, what about dictionary comprehensions?

Expected Output:

>>> countChar('google')
    {'e': 1, 'g': 2, 'l': 1, 'o': 2}
    >>> countLetters('apple')
    {'a': 1, 'e': 1, 'l': 1, 'p': 2}
    >>> countLetters('')
    {}

Code (I'm a beginner):

def countChar(word):
    l = []
    #get a list from word
    for c  in word: l.append(c)
    sortedList = sorted(l)
    uniqueSet = set(sortedList)
    return {item:word.count(item) for item in uniqueSet }

What is the problem with this code? Why do I get this SyntaxError?

return { item:word.count(item) for item in uniqueSet }
^
SyntaxError: invalid syntax
like image 624
newbie Avatar asked Sep 11 '25 02:09

newbie


1 Answers

If you're on Python 2.7 or newer:

{item: word.count(item) for item in set(word)}

works fine. You don't need to sort the list before you set it. You also don't need to turn the word into a list. Also, you're on a new enough Python to use collections.Counter(word) instead.

If you're on an older version of Python, you can't use dict comprehensions, you need to use a generator expression with the dict constructor:

dict((item, word.count(item)) for item in set(word))

This still requires you to iterate over word len(set(word)) times, so try something like:

from collections import defaultdict
def Counter(iterable):
    frequencies = defaultdict(int)
    for item in iterable:
        frequencies[item] += 1
    return frequencies
like image 61
agf Avatar answered Sep 12 '25 16:09

agf