【问题标题】:Convert list of lists to custom dictionary将列表列表转换为自定义字典
【发布时间】:2015-05-14 13:19:40
【问题描述】:

我尝试将列表列表转换为自定义字典没有成功。 我创建了以下输出,保存在两个列表中:

headers = ['CPU', 'name', 'id', 'cused', 'callc', 'mused', 'mallc']

result = [['1/0', 'aaa', '10', '0.1', '15', '10.73', '16.00'],
          ['1/0', 'bbb', '10', '0.1', '20', '11.27', '14.00'],
          ['1/0', 'ccc', '10', '0.2', '10', '11.50', '15.00'],
          ['1/0', 'aaa', '10', '1.1', '15', '15.10', '23.00']]

Formatted output:
headers:
    slot name           id  cused callc mused  mallc 
    result:
     1/0 aaa            10  0.1    15   10.73 16.00
     2/0 bbb            25  0.1    20   11.39 14.00
     1/0 ccc            10  0.2    10   11.50 15.00
     1/0 aaa            10  1.1    15   15.10 23.00

前 n 列(本例中为 3 列)应用于将键名与所有剩余列作为输出值连接。 我想将其转换为以下格式的字典:

slot.<slot>.name.<name>.id.<id>.cused:<value>,
slot.<slot>.name.<name>.id.<id>.callc:<value>,
slot.<slot>.name.<name>.id.<id>.mused:<value>,
slot.<slot>.name.<name>.id.<id>.mallc:<value>,
...

例如:

dictionary = { 
'slot.1/0.name.aaa.id.10.cused':10, 
'slot.1/0.name.aaa.id.25.callc':15,
'slot.1/0.name.aaa.id.10.mused':10.73, 
'slot.1/0.name.aaa.id.10.mallc':16.00,
'slot.2/0.name.bbb.id.10.cused':0.1,
...
'slot.<n>.name.<name>.id.<id>.<value_name> <value>
}

你能告诉我怎么做吗?

【问题讨论】:

  • 显示列表,而不是你的程序如何输出它
  • 在这里 - 我已经编辑了帖子
  • 非常感谢大家的帮助。没想到回复这么快。
  • 一项附加修改 - 如果我想选择用于创建键名和输出值的标题名称,该怎么办?例如仅打印:'slot.1/0.name.bbb.cused' values?

标签: python list dictionary tuples


【解决方案1】:

更新 - OP 添加了原始列表

现在您已经更新了问题以显示原始列表,这就更容易了:

headers = ['CPU', 'name', 'id', 'cused', 'callc', 'mused', 'mallc']

result = [['1/0', 'aaa', '10', '0.1', '15', '10.73', '16.00'],
          ['1/0', 'bbb', '10', '0.1', '20', '11.27', '14.00'],
          ['1/0', 'ccc', '10', '0.2', '10', '11.50', '15.00'],
          ['1/0', 'aaa', '10', '1.1', '15', '15.10', '23.00']]

results = {}
for r in result:
    slot, name, _id = r[:3]
    results.update(
        {'slot.{}.name.{}.id.{}.{}'.format(slot, name, _id, k) : v
             for k, v in zip(headers[3:], r[3:])})

>>> from pprint import pprint
>>> pprint(results)
{'slot.1/0.name.aaa.id.10.callc': '15',
 'slot.1/0.name.aaa.id.10.cused': '1.1',
 'slot.1/0.name.aaa.id.10.mallc': '23.00',
 'slot.1/0.name.aaa.id.10.mused': '15.10',
 'slot.1/0.name.bbb.id.10.callc': '20',
 'slot.1/0.name.bbb.id.10.cused': '0.1',
 'slot.1/0.name.bbb.id.10.mallc': '14.00',
 'slot.1/0.name.bbb.id.10.mused': '11.27',
 'slot.1/0.name.ccc.id.10.callc': '10',
 'slot.1/0.name.ccc.id.10.cused': '0.2',
 'slot.1/0.name.ccc.id.10.mallc': '15.00',
 'slot.1/0.name.ccc.id.10.mused': '11.50'}

基于原始文件的答案

以下代码将构造所需的字典 (results)。这个想法是文件中的每个非标题行都被空格分割成字段,并且这些字段在字典理解中用于为每一行构造一个字典,然后用于更新结果字典。

with open('data') as f:
    # skip the 3 header lines
    for i in range(3):
        _ = next(f)

    STAT_NAMES = 'cused callc mused mallc'.split()
    results = {}
    for line in f:
        line = line.split()
        slot, name, _id = line[:3]
        results.update(
            {'slot.{}.name.{}.id.{}.{}'.format(slot, name, _id, k) : v
                 for k, v in zip(STAT_NAMES, line[3:])})

输出

>>> from pprint import pprint
>>> pprint(results)
{'slot.1/0.name.aaa.id.10.callc': '15',
 'slot.1/0.name.aaa.id.10.cused': '1.1',
 'slot.1/0.name.aaa.id.10.mallc': '23.00',
 'slot.1/0.name.aaa.id.10.mused': '15.10',
 'slot.1/0.name.ccc.id.10.callc': '10',
 'slot.1/0.name.ccc.id.10.cused': '0.2',
 'slot.1/0.name.ccc.id.10.mallc': '15.00',
 'slot.1/0.name.ccc.id.10.mused': '11.50',
 'slot.2/0.name.bbb.id.25.callc': '20',
 'slot.2/0.name.bbb.id.25.cused': '0.1',
 'slot.2/0.name.bbb.id.25.mallc': '14.00',
 'slot.2/0.name.bbb.id.25.mused': '11.39'}

【讨论】:

    【解决方案2】:

    试试这个,注意:我改变了“插槽”而不是“CPU”

    headers = ['slot', 'name', 'id', 'cused', 'callc', 'mused', 'mallc']
    
    result = [['1/0', 'aaa', '10', '0.1', '15', '10.73', '16.00'],
              ['1/0', 'bbb', '10', '0.1', '20', '11.27', '14.00'],
              ['1/0', 'ccc', '10', '0.2', '10', '11.50', '15.00'],
              ['1/0', 'aaa', '10', '1.1', '15', '15.10', '23.00']]
    
    #I get: [['1/0', '1/0', '1/0', '1/0'], ['aaa', 'bbb', 'ccc', 'aaa'], ....
    transpose_result = map(list, zip(*result))
    
    #I get: {'slot': ['1/0', '1/0', '1/0', '1/0'], 
    #        'mallc': ['16.00', '14.00', '15.00', '23.00'], ...
    data = dict(zip(headers, transpose_result))
    
    d = {}
    for reg in ("cused", "callc", "mused", "mallc"):
      for i, val in enumerate(data[reg]):
        key = []
        for reg2 in ("slot", "name", "id"):
          key.append(reg2)
          key.append(data[reg2][i])
        key.append(reg)
        d[".".join(key)] = val
    

    你进入d

    {
    'slot.1/0.name.bbb.id.10.cused': '0.1',
    'slot.1/0.name.aaa.id.10.cused': '1.1', 
    'slot.1/0.name.bbb.id.10.callc': '20',
    'slot.1/0.name.aaa.id.10.mallc': '23.00', 
    'slot.1/0.name.aaa.id.10.callc': '15', 
    'slot.1/0.name.ccc.id.10.mallc': '15.00', 
    'slot.1/0.name.ccc.id.10.mused': '11.50', 
    'slot.1/0.name.aaa.id.10.mused': '15.10', 
    'slot.1/0.name.ccc.id.10.cused': '0.2', 
    'slot.1/0.name.ccc.id.10.callc': '10', 
    'slot.1/0.name.bbb.id.10.mallc': '14.00',
    'slot.1/0.name.bbb.id.10.mused': '11.27'}
    

    【讨论】:

    • 非常感谢。这个答案非常适合我。
    • @PaVliK 我很高兴
    【解决方案3】:
      import itertools
    
      headers = 'slot name id cused callc mused mallc'.split()
      result = ['1/0 aaa 10 0.1 15 10.73 16.00'.split(),
                '2/0 bbb 25 0.1 20 11.39 14.00'.split()]
      key_len = 3
    
      d = {}
      for row in result:
          key_start = '.'.join(itertools.chain(*zip(headers, row[:key_len])))
          for key_end, val in zip(headers[key_len:], row[key_len:]):
              d[key_start + '.' + key_end] = val
    

    【讨论】:

      【解决方案4】:

      另一种具有正确类型的 cused、callc、mused 和 mallc 解决方案

      labels = ['slot','name','id','cused','callc','mused','mallc']
      data = ['1/0 aaa            10  0.1    15   10.73 16.00',
      '2/0 bbb            25  0.1    20   11.39 14.00',
      '1/0 ccc            10  0.2    10   11.50 15.00',
      '1/0 aaa            10  1.1    15   15.10 23.00']
      
      data = [tuple(e.split()) for e in data]
      data = [zip(labels, e) for e in data]
      results = dict()
      
      for e in data:
          s = '%s.%s.%s' % tuple(['.'.join(e[i]) for i in range(3)])
          for i in range(3,7):
              results['%s.%s' % (s, e[i][0])] = int(e[i][1]) if i == 4 else float(e[i][1])
      
      print results
      

      【讨论】:

        猜你喜欢
        • 2017-04-23
        • 2021-10-13
        • 2015-07-23
        • 1970-01-01
        • 2014-01-20
        • 2020-05-23
        • 2019-06-11
        相关资源
        最近更新 更多