Python:将列表拆分为dicts列表?

时间:2009-12-23 04:21:20

标签: python list dictionary

刚开始使用python并且知道得知道我什么都不知道。我想找到将列表拆分为dicts列表的替代方法。示例列表:

data = ['ID:0:0:0',
        'Status:Ok',
        'Name:PhysicalDisk0:0:0',
        'State:Online',
        'FailurePredicted:No',
        'ID:0:0:1',
        'Status:Ok',
        'Name:PhysicalDisk0:0:1',
        'State:Online',
        'FailurePredicted:No']

完成的词典列表:

[{'Status': 'Ok',
  'State': 'Online',
  'ID': '0:0:0',
  'FailurePredicted': 'No',
  'Name': 'PhysicalDisk0:0:0'},
 {'Status': 'Ok',
  'State': 'Online',
  'ID': '0:0:1',
  'Name': 'PhysicalDisk0:0:1',
  'FailurePredicted': 'No'}]

该列表包含需要多个dicts的重复元素,并且列表的长度不同。我的代码似乎可以简化,只要我更了解Python。我目前的代码:

删除代码它不起作用。 :(

----------- File output as requested -------------------

# omreport storage pdisk controller=0
List of Physical Disks on Controller PERC 5/i Integrated (Embedded)

Controller PERC 5/i Integrated (Embedded)
ID                        : 0:0:0
Status                    : Ok
Name                      : Physical Disk 0:0:0
State                     : Online
Failure Predicted         : No
Progress                  : Not Applicable
Type                      : SAS
Capacity                  : 136.13 GB (146163105792 bytes)
Used RAID Disk Space      : 136.13 GB (146163105792 bytes)
Available RAID Disk Space : 0.00 GB (0 bytes)
Hot Spare                 : No
Vendor ID                 : DELL    
Product ID                : ST3146755SS     
Revision                  : T107
Serial No.                : 3LN1EF0G            
Negotiated Speed          : Not Available
Capable Speed             : Not Available
Manufacture Day           : 07
Manufacture Week          : 24
Manufacture Year          : 2005
SAS Address               : 5000C50004731C35

ID                        : 0:0:1
Status                    : Ok
Name                      : Physical Disk 0:0:1
State                     : Online
Failure Predicted         : No
Progress                  : Not Applicable
Type                      : SAS
Capacity                  : 136.13 GB (146163105792 bytes)
Used RAID Disk Space      : 136.13 GB (146163105792 bytes)
Available RAID Disk Space : 0.00 GB (0 bytes)
Hot Spare                 : No
Vendor ID                 : DELL    
Product ID                : ST3146755SS     
Revision                  : T107
Serial No.                : 3LN1EF88            
Negotiated Speed          : Not Available
Capable Speed             : Not Available
Manufacture Day           : 07
Manufacture Week          : 24
Manufacture Year          : 2005
SAS Address               : 5000C500047320B9

5 个答案:

答案 0 :(得分:8)

result = [{}]
for item in data:
    key, val = item.split(":", 1)
    if key in result[-1]:
        result.append({})
    result[-1][key] = val

答案 1 :(得分:1)

import re

results = []
temp = {}
for item in data:
    (key, value) = re.search('(.*?):(.*)', item).groups()
    if temp.has_key(key): temp = {}
    temp[key] = value
    if temp not in results: results.append(temp)

答案 2 :(得分:1)

如果您没有比“每次重复键都表示需要启动新词典”更多的信息,那么您的代码只能略有改进,例如:

results = []
curd = {}
for x in data:
  k, v = x.split(':', 1)
  if k in curd:
    results.append(curd)
    curd = {}
  curd[k] = v
results.append(curd)

即,不需要保留中间列表tmp而不是中间词典curd。语义略有不同 - 只有当键和值都重合时才会启动一个新的dict(例如'Status:Borked'之类的项将“践踏”从'Status:Ok'构建的一个项目,例如) ,我只把密钥作为标识符(所以,在这种情况下没有践踏) - 你确定你实现的确切语义是你需要的吗?

答案 3 :(得分:0)

ret = []
ITEMS_AMOUNT = 5 
while True:
        tmp = {}
        for i in data[0:ITEMS_AMOUNT]:
                tmp.update(dict([i.split(':', 1)]))
        ret.append(tmp)

        if len(data) == ITEMS_AMOUNT:
                break
        data = data[ITEMS_AMOUNT:]

print ret 

答案 4 :(得分:0)

d=dict([])
c=0
whatiwant=["ID","Status","Name","State","Failure Predicted"]
for line in open("file"):
    line=line.rstrip()
    sline=line.split(":",1)
    sline[0]=sline[0].strip()
    if sline[0]=="ID":
        c+=1
        d.setdefault(c,[])
    if sline[0] in whatiwant:
        d[c].append((sline[0],' '.join(sline[1:])))
for i,j in d.iteritems():
    print i,j

输出

$ ./python.py
1 [('ID', ' 0:0:0'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:0'), ('State', ' Online'), ('Failure Predicted', ' No')]
2 [('ID', ' 0:0:1'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:1'), ('State', ' Online'), ('Failure Predicted', ' No')]