将列表列表转换为自定义词典

时间:2015-05-14 13:19:40

标签: python list dictionary tuples

我尝试将列表列表转换为自定义词典失败了。 我创建了以下输出保存在两个列表中:

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>
}

你能告诉我怎么做吗?

4 个答案:

答案 0 :(得分: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'}

答案 1 :(得分:0)

试试这个,注意:我改变了#34;插槽&#34;而不是&#34; CPU&#34;

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'}

答案 2 :(得分:0)

  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

答案 3 :(得分:0)

另一种解决方案,其中包含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