如何将列表转换成字典

时间:2020-10-27 14:16:30

标签: python python-3.x list dictionary

我想将列表转换成字典,其中key是列表中指定的整数,而value是列表中数字的频率。 例如,

list = [10,10,10,20,20,40,50]

然后字典看起来像

dict = {'10':3,'20':2,'40':1,'50':1}。

此转换方法是什么?

1 个答案:

答案 0 :(得分:1)

nlist = [10,10,10,20,20,40,50]
ndict = {}

for item in set(nlist):
    ndict[item] = nlist.count(item)

创建ndict:

{40: 1, 10: 3, 20: 2, 50: 1}