将Python字典转换为List,其中dict键位于列表的第一个索引处

时间:2017-07-17 16:20:56

标签: python python-3.x dictionary

我有下面的词典列表,

[
    {
        "animal": "lion",
        "color": "yellow"
    },
    {
        "animal": "elephant",
        "color": "black" 
    }
]

我需要输出作为列表的列表,格式如下,

[
    ["animal","color"],
    ["lion","yellow"],
    ["elephant","black"]
]

2 个答案:

答案 0 :(得分:3)

首先,从列表中的第一个字典中提取密钥。然后,通过将这些键应用于每个字典来构建列表。

keys = sorted(list_of_dicts[0].keys())
table = [keys] + [[d[k] for k in keys] for d in list_of_dicts]
# [['animal', 'color'], ['lion', 'yellow'], ['elephant', 'black']]

答案 1 :(得分:1)

你可以试试这个:

import itertools
l = [
 {
   "animal": "lion",
    "color": "yellow"
 },
 {
    "animal": "elephant",
    "color": "black"
 }
]

headers = list(set(itertools.chain.from_iterable([i.keys() for i in l])))

headers.extend([i.values() for i in l])
print(headers)

输出:

[['animal', 'color'], ['lion', 'yellow'], ['elephant', 'black']]