如何在python中将字典表转换为列表?

时间:2013-12-03 13:41:52

标签: python list dictionary

def change_table(table):

    """
    (dict) -> table

从字典列表返回表格列表,其中表格列表是项目的行

change_table({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]})

>>> [['a', 'b', 'c'], [1, 1, 1], [2, 2, 2], [3, 3, 3]]
"""

table_list = []
item_table = []
item_row = []

column_row = []

for key in table:
    column_row.append(key)
    i = 0
    for item in range(len(table[key])):


        item_table.append(table[key][item])

        item_row.insert(i, item_table)
        i = i + 1

table_list.extend(column_row)
table_list.extend(item_row)
return table_list

这不符合我的要求。非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

[[key for key in table.keys()]] + [[val[i] for val in table.values()] for i in range(len(table.values()[0]))]

编辑:下面的注释有效,键顺序与原始表中的顺序不同,但保留了列顺序。使用排序(键)将中断顺序:

table = {'a':['a1','a2','a3'],'b':['b1','b2','b3'],'c':['1','2','3']}
[[key for key in sorted(table.keys())]] + [[val[i] for val in table.values()] for i in range(len(table.values()[0]))]
>>>[['a', 'b', 'c'], ['a1', '1', 'b1'], ['a2', '2', 'b2'], ['a3', '3', 'b3']]

答案 1 :(得分:0)

在Python 2中:

def change_table(d):
    values = d.values()
    return sorted(d.keys()) + [[item[i] for item in values] 
                          for i in range(len(values[0]))]

if __name__ == '__main__':
    print(change_table({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}))

...或Python 3:

def change_table(d):
    values = list(d.values())
    return [sorted(d.keys())] + [[item[i] for item in values] 
                                for i in range(len(values[0]))]

if __name__ == '__main__':
    print(change_table({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}))