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

后端 未结 2 1183
猫巷女王i
猫巷女王i 2020-12-29 04:07

I know about list comprehensions, what about dictionary comprehensions?

Expected Output:

>>> countChar(\'google\')
    {\'e\': 1, \'g\': 2,          


        
2条回答
  •  情深已故
    2020-12-29 05:07

    edit: As agf pointed out in comments and the other answer, there is a dictionary comprehension for Python 2.7 or newer.

    def countChar(word):
        return dict((item, word.count(item)) for item in set(word))
    
    >>> countChar('google')
    {'e': 1, 'g': 2, 'o': 2, 'l': 1}
    >>> countChar('apple')
    {'a': 1, 'p': 2, 'e': 1, 'l': 1}
    

    There is no need to convert word to a list or sort it before turning it into a set since strings are iterable:

    >>> set('google')
    set(['e', 'o', 'g', 'l'])
    

    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.

提交回复
热议问题