python - 制作 Counter.most_common 返回字典

标签 python dictionary python-collections

我使用了文档中的示例:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

我怎样才能使结果成为:

{ 'a': 5, 'r' :2 , 'b' :2}

假设我们想保留 Counter().most_common() 代码?

最佳答案

dict将轻松做到这一点:

>>> dict(Counter('abracadabra').most_common(3))
{'a': 5, 'r': 2, 'b': 2}
>>>

为了进一步引用,这里是 help(dict) 返回的部分内容:

     dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v

关于python - 制作 Counter.most_common 返回字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625443/

相关文章:

ios - Swift,不同类型的嵌套字典

python - Python 集合模块中大写的意义?

python 乘以两个收集计数器

Python PyQt 像素图更新崩溃

python - 如何找到正确的 xpath 并循环遍历表?

C++ 空映射赋值 : equals vs insert

python - 检索集合的输入。计数器输出

python - 在 VS Code 中设置 python 自动完成

python - 如果字符串等于 Python 中的正则表达式?

java - 哈希表 "method put() is undefined for the type HashMap"