Skip to content Skip to sidebar Skip to footer

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} >>> coun

Solution 1:

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 wordlen(set(word)) times, so try something like:

from collections import defaultdict
defCounter(iterable):
    frequencies = defaultdict(int)
    for item in iterable:
        frequencies[item] += 1return frequencies

Solution 2:

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

defcountChar(word):
    returndict((item, word.count(item)) for item inset(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.

Post a Comment for "Are There Dictionary Comprehensions In Python? (problem With Function Returning Dict)"