转换dicts列表中的一列

时间:2017-02-03 00:36:31

标签: python excel dictionary

我想在一个字典列表中转换Excel中的一列。有可能吗?

输入样本:

A     B      C      D      E
0.00  10.00  22.00  10.00  15.00
1.00  81.29  28.00  23.33  18.38

输出样本:

somefunc(column="A")
[{ "A": 0.00 }, { "A": 1.00 }]

目前我正在使用此代码,然后删除额外的密钥..这根本没有意义。

def to_dict(file_path, header_index=0, sheet_index=0):
    data, keys, sheet = {}, [], _read(file_path).sheet_by_index(sheet_index)
    for col_index in xrange(0, sheet.ncols):
        keys.append(sheet.cell(header_index, col_index).value.encode("utf-8"))
    for row_index in xrange(2, sheet.nrows):
        for col_index in xrange(sheet.ncols):
            if keys[col_index] not in data.keys():
                data[keys[col_index]] = []
            data[keys[col_index]].append(sheet.cell(row_index, col_index).value)
    return data

1 个答案:

答案 0 :(得分:0)

我认为你可以这样做:

def to_dict(file_path, header_index=0, sheet_index=0):
    result = []
    sheet = _read(file_path).sheet_by_index(sheet_index)
    for row_index in xrange(2, sheet.nrows):
        row_dict = {}
        for col_index in xrange(sheet.ncols):
            key = sheet.cell(header_index, col_index).value.encode("utf-8")
            row_dict[key] = sheet.cell(row_index, col_index).value
        result.append(row_dict)
    return result