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
edit: As agf pointed out in comments and the other answer, there is a dictionary comprehension for Python 2.7 or newer.
There is no need to convert
wordto a list or sort it before turning it into a set since strings are iterable:There is no dictionary comprehension with for Python 2.6 and below, which could be why you are seeing the syntax error. The alternative is to create a list of key-value tuples using a comprehension or generator and passing that into the
dict()built-in.