Python中有字典理解吗? (函数返回dict的问题)

时间:2011-09-01 21:03:40

标签: python dictionary python-2.x

我知道列表理解,字典理解怎么样?

预期产出:

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

代码(我是初学者):

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 }

此代码有什么问题?为什么我会得到这个SyntaxError

return { item:word.count(item) for item in uniqueSet }
^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:64)

如果您使用的是Python 2.7或更高版本:

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

工作正常。在设置列表之前,无需对列表进行排序。您也不需要将单词转换为列表。此外,您正在使用足够新的Python来代替collections.Counter(word)

如果您使用的是旧版本的Python,则无法使用dict理解,则需要使用dict构造函数的生成器表达式:

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

这仍然需要您迭代word len(set(word))次,所以请尝试以下方法:

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

答案 1 :(得分:32)

编辑:正如agf在评论和其他答案中指出的那样,Python 2.7或更新版本有字典理解。

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}

由于字符串是可迭代的,因此无需将word转换为列表或对其进行排序,因为字符串是可迭代的:

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

对于Python 2.6及更低版本,没有字典理解,这可能是您看到语法错误的原因。另一种方法是使用理解或生成器创建键值元组列表,并将其传递到dict()内置函数中。