如何从包含重复值的列表中创建字典

时间:2017-04-16 19:26:13

标签: python python-3.x dictionary

我是python的新手,我在尝试将以下列表转换为字典时已经挣扎了一段时间。

lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99, 
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230', 
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32, 
'AB_MK1230',  'MK12303', 89.26, 'AB_MK1230',  'MK12301', 91.75,'AB_MK1230', 
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49, 
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230', 
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34, 
'AB_MK1230', 'MK12303', 76.88] 

AB_MK1230是母扇区,MK12303,MK12301和MK12302是子扇区。我的输出是一个字典,其中包含每个子扇区的键和父扇区以及浮点值作为该键的值,如下所示。

dict = {MK12301: AB_MK1230, 93.82, 94.81, 91.75, 93.49, 86.47, 79.24
        MK12302: AB_MK1230, 89.99, 94.67, 90.32, 88.54, 84.79, 80.34
        MK12303: AB_MK1230, 86.17, 87.50, 89.26, 92.50, 86.57, 76.88 }

我已经阅读了https://docs.python.org/3/tutorial/datastructures.html?highlight=dictionaries的一些文档,但我仍然无法找到解决方案。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

我们遍历列表,在(parent, child, value) - 订单中一次解包三个项目。我们使用(parent, child)作为字典中的键,然后将值添加到set

import itertools
import collections

lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99, 
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230', 
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32, 
'AB_MK1230',  'MK12303', 89.26, 'AB_MK1230',  'MK12301', 91.75,'AB_MK1230', 
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49, 
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230', 
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34, 
'AB_MK1230', 'MK12303', 76.88]

d = collections.defaultdict(set)
for parent, child, value in itertools.zip_longest(*[iter(lst)]*3, fillvalue=None):
    d[(parent, child)].add(value)

d现在是一个像

这样的字典
defaultdict(set,
            {('AB_MK1230', 'MK12301'): {79.24,
              86.47,
              91.75,
              93.49,
              93.82,
              94.81},
             ('AB_MK1230', 'MK12302'): {80.34,
              84.79,
              88.54,
              89.99,
              90.32,
              94.67},
             ('AB_MK1230', 'MK12303'): {76.88,
              86.17,
              86.57,
              87.5,
              89.26,
              92.5}})

目前还不完全清楚您的最终数据结构应该如何。如果您只想parent作为顶级键,则可以使用嵌套的defaultdict ...