如何将列表列表更改为键值?

时间:2017-05-03 16:06:59

标签: python csv

我想这样转换数据: csv中的第一行是键,以下行是值。我怎么能这样做?

所以我希望密钥是' SkuPartNumber' ActiveUnits',' ConsumedUnits',以及值是它下面的行。

目标是我可以按照以下方式查询记录并将值存储在其他位置。

for i in records:
 ...
 results.append((i['SkuPartNumber'],i['ActiveUnits'],i['ConsumedUnits'])

代码:

>>>cmd = ['C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe', 'script.ps1']
>>>subprocess.call(cmd)
>>> with open ('sku.csv', 'r') as sku:
...     reader = csv.reader(sku)
...     records = list(reader)
...
>>> type(records)
<class 'list'>
>>> pprint(records)
[['SkuPartNumber', 'ActiveUnits', 'ConsumedUnits'],
 ['EXCHANGESTANDARD', '1', '1'],
 ['O365_BUSINESS_PREMIUM', '4', '4']]
>>>

感谢一些帮助。

预期结果:

[{
    "SkuPartNumber": "EXCHANGESTANDARD",
    "ActiveUnits": 1,
    "ConsumedUnits": 1
}, {
    "SkuPartNumber": "O365_Business_Premium",
    "ActiveUnits": 4,
    "ConsumedUnits": 4
}]

4 个答案:

答案 0 :(得分:3)

我不知道您为什么要将子进程,powershell和其他主题纳入其中,但您需要的是来自DictReader模块的csv

>>> from csv import DictReader
>>> filedata = '''SkuPartNumber,ActiveUnits,ConsumedUnits
... EXCHANGESTANDARD,1,1
... O365_BUSINESS_PREMIUM,4,4
... '''
>>> list(DictReader(filedata.splitlines()))
[{'ActiveUnits': '1', 'ConsumedUnits': '1', 'SkuPartNumber': 'EXCHANGESTANDARD'}, {'ActiveUnits': '4', 'ConsumedUnits': '4', 'SkuPartNumber': 'O365_BUSINESS_PREMIUM'}]

在实际代码中,只需使用list(DictReader(f)),其中f是已打开文件的名称。

答案 1 :(得分:0)

records = [['SkuPartNumber', 'ActiveUnits', 'ConsumedUnits'],
           ['EXCHANGESTANDARD', '1', '1'],
           ['O365_BUSINESS_PREMIUM', '4', '4']]


recorddictlist = [dict(SkuPartNumber=r[0],
                       ActiveUnits=r[1],
                       ConsumedUnits=r[2]) for r in records[1:]]

print(recorddictlist)

这不是最灵活的,但假设您的子流程输出稳定,我发现它最容易阅读。

否则您可以在评论中使用csv.DictReader

答案 2 :(得分:0)

# new empty list of records in new format
transformed_records = []

# iterate over records, skipping the first list which is key names
for values in records[1:]:

    # fresh dict to hold this row
    newdict = {}

    # iterate over each value
    for position,value in enumerate(values):

        # fetch key name from first list in records
        key = records[0][position]
        newdict[key] = value

    # add dict to the list
    transformed_records.append(newdict)

答案 3 :(得分:0)

我能想到的最简单的方式:

from pprint import pprint

records = [['SkuPartNumber', 'ActiveUnits', 'ConsumedUnits'],
           ['EXCHANGESTANDARD', '1', '1'],
           ['O365_BUSINESS_PREMIUM', '4', '4']]

fields = records[0]
result = [dict(zip(fields, record)) for record in records[1:]]
pprint(result)

输出:

[{'ActiveUnits': '1',
  'ConsumedUnits': '1',
  'SkuPartNumber': 'EXCHANGESTANDARD'},
 {'ActiveUnits': '4',
  'ConsumedUnits': '4',
  'SkuPartNumber': 'O365_BUSINESS_PREMIUM'}]