Python中有字典推导吗?(函数返回字典的问题)

25 投票
2 回答
29119 浏览
提问于 2025-04-17 01:09

我知道列表推导式,那字典推导式呢?

期望的输出:

>>> 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 个回答

67

如果你使用的是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
33

编辑: 正如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()这个内置函数。

撰写回答