Python:将此列表转换为字典

3 投票
4 回答
13817 浏览
提问于 2025-04-16 05:39

我遇到了一个问题,但我不知道怎么用Python编程。

我有一个列表,内容是list[10, 10, 10, 20, 20, 20, 30]

我想把它变成一个字典,像这样

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

我该怎么做呢?

4 个回答

1

像这样

l = [10, 10, 10, 20, 20, 20, 30]
uniqes = set(l)
answer = {}
for i in uniques:
    answer[i] = l.count(i)

answer 现在就是你想要的字典

希望这对你有帮助

4

还有一种方法,不使用 setCounter

d = {}
x = [10, 10, 10, 20, 20, 20, 30]
for j in x:
    d[j] = d.get(j,0) + 1

补充说明:对于一个包含1000000个元素的列表,其中有100个独特的项目,这种方法在我的笔记本电脑上运行需要0.37秒,而使用 set 的方法则需要2.59秒。对于只有10个独特项目的情况,前者需要0.36秒,而后者只需要0.25秒。

补充说明:使用 defaultdict 的方法在我的笔记本电脑上只需要0.18秒。

16
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

撰写回答