【问题标题】:Convert a list of lists into a nested dictionary将列表列表转换为嵌套字典
【发布时间】:2016-07-26 14:23:17
【问题描述】:

我正在尝试将列表列表转换为嵌套字典:

我的代码:

csv_data={}
    for key, value in csv_files.iteritems():
        if key in desired_keys:
            csv_data[key]=[]

            for element in value:
                csv_data[key].append(element[1:])

这段代码给了我以下信息:

{   'Network': [
        ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
        ['0.3', '0.1', '0.3']
    ],
    'CPU': [
        ['Processor Time', 'User Time', 'Privileged Time'],
        ['13.8', '6.7', '7.2']
    ]
}

所以在这种情况下,每个“值”是一个包含两个列表的列表,包含一个“标题”列表和一个“数值”列表

但是我想生成如下格式:

{   'Network': {
        'Total KB/sec':0.3,
        'Sent KB/sec':0.1,
        'Received KB/sec':0.3
    },
    'CPU': {
        'Processor Time':'13.8',
        'User Time': '6.7',
        'Privileged Time': '7.2'
    }
}

我应该如何更改我的代码以产生此输出?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    假设我在您的一个键Network 上演示了zip() 的使用:

    >>> network = [
        ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
        ['0.3', '0.1', '0.3']
    ]
    

    zip()这两个列表将产生一组元组,只需在其上调用dict()即可将其转换为字典。换句话说,

    >>> dict(zip(network[0], network[1]))
    {'Received KB/sec': '0.3', 'Sent KB/sec': '0.1', 'Total KB/sec': '0.3'}
    

    重复CPU 键。

    【讨论】:

    • 我就先把我写的单行本放在这里,希望对OP有用,不要浪费。 csv_data[key]= dict(zip(*(row[1:] for row in value)))
    【解决方案2】:

    zip() 对于同时迭代列表非常方便,使用dict() 转换为字典变得非常容易。

    def to_dict(dic):
        for key, value in dic.iteritems():
            dic[key] = dict(zip(* value))
        return dic
    

    示例输出:

    d = {'Network': [['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
    ['0.3', '0.1', '0.3']],
    'CPU': [['Processor Time', 'User Time', 'Privileged Time'],
    ['13.8', 6.7', '7.2']]}
    
    print to_dict(d)
    >>> {'Network': {'Sent KB/sec': '0.1', 'Total KB/sec': '0.3', 'Received 
    KB/sec': '0.3'}, 'CPU': {'Processor Time': '13.8', 'Privileged Time': 
    '7.2', 'User Time': '6.7'}}
    

    它是如何工作的?

    当您在列表上使用 zip 函数时,它会返回 元组对 的列表,并通过耦合每个列表来迭代各个级别的列表,将它们视为 并行列表跨越列表的元素在它们的相应索引处。所以如果我们隔离zip(* value)操作我们可以清楚的看到操作的结果:

    >>> [('Total KB/sec', '0.3'), ('Sent KB/sec', '0.1'), ('Received 
        KB/sec', '0.3')]
        [('Processor Time', '13.8'), ('User Time', '6.7'), ('Privileged 
        Time', '7.2')]
    

    【讨论】:

      【解决方案3】:

      没有zip的方法

      dct = {   'Network': [
              ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
              ['0.3', '0.1', '0.3']
          ],
          'CPU': [
              ['Processor Time', 'User Time', 'Privileged Time'],
              ['13.8', '6.7', '7.2']
          ]
      }
      
      for key, val in dct.items():
          placeholder_dct= {}
          for i in range(len(val[0])):
              placeholder_dct[val[0][i]] = val[1][i]
          dct[key] = placeholder_dct
      
      print(dct)
      

      【讨论】:

        【解决方案4】:

        试试这个代码:

        {x:{z:t for z,t in (dict(zip(y[0], y[1]))).items()} for x,y in data.items()}
        

        输入时:

        data={   'Network': [
            ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
            ['0.3', '0.1', '0.3']
        ],
        'CPU': [
            ['Processor Time', 'User Time', 'Privileged Time'],
            ['13.8', '6.7', '7.2']
        ]}
        

        输出:

        res= {'Network': {'Sent KB/sec': '0.1', 'Total KB/sec': '0.3', 'Received KB/sec': '0.3'}, 'CPU': {'Processor Time': '13.8', 'Privileged Time': '7.2', 'User Time': '6.7'}}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-03
          • 1970-01-01
          • 2017-07-29
          • 2011-08-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多