Python:将此列表转换为字典

标签 python list dictionary formatting

我有一个问题,不知道如何用 python 编码。

我有一个列表[10, 10, 10, 20, 20, 20, 30]

我希望它在这样的字典中

{"10": 1, "20":  3, "30" : 1}

我怎样才能做到这一点?

最佳答案

from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})

如果您真的想将键转换为字符串,那是一个单独的步骤:

dict((str(k), v) for k, v in c.iteritems())

这个类是 Python 2.7 的新类;对于早期版本,使用此实现:

http://code.activestate.com/recipes/576611/


编辑:把它放在这里因为 SO 不会让我将代码粘贴到评论中,

from collections import defaultdict
def count(it):
    d = defaultdict(int)
    for j in it:
        d[j] += 1
    return d

关于Python:将此列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956206/

相关文章:

python - 用 SED 替换字符串

python - 如何从具有不同长度列表的字典创建字典列表

python - Pyspark - 2 个数据帧之间的区别 - 识别插入、更新和删除

python - 从非系统安装的 Python 执行 Python 脚本

python - 在 postgreSQL 中启用查询缓存以提高性能

python - 将属性添加到类列表以返回具有特定属性的所有对象

不分配变量的 Python 列表

python - 通过在 Pandas 数据框中增加 5 的增量来对数字进行分组

java - 使用 Java 8 Lambda 表达式合并映射流

python - 具有多行值的 PEP8 多行字典