如何 "flatten" python 中的词典列表

How to "flatten" list of dictionaries in python

我有一个字典列表,如下所示:

test_dict = [{'id': 0, 'name': ['Jim'], 'lastname': ['kkk']}, {'id': 1, 'name': ['John'], 'lastname': ['lll']}]
test_dict


[{'id': 0, 'name': ['Jim'], 'lastname': ['kkk']},
 {'id': 1, 'name': ['John'], 'lastname': ['lll']}]

我想创建另一个字典作为键,test_dictid

我正在寻找的输出如下所示:

test_dict_f = {'0': {'name': ['Jim'], 'lastname': ['kkk']}, 
              '1': {'name': ['John'], 'lastname': ['lll']}}
test_dict_f

{'0': {'name': ['Jim'], 'lastname': ['kkk']},
 '1': {'name': ['John'], 'lastname': ['lll']}}

有什么想法可以实现吗?

在一行中试试这个:

result = {str(i["id"]): {"name": i["name"], "lastname": i["lastname"]} for i in test_dict}

结果将是:

{'0': {'name': ['Jim'], 'lastname': ['kkk']},
 '1': {'name': ['John'], 'lastname': ['lll']}}

这是另一种方法,它不依赖于 'id' 以外的任何键的知识。请注意,这是破坏性的:

test_dict = [{'id': 0, 'name': ['Jim'], 'lastname': ['kkk']}, {'id': 1, 'name': ['John'], 'lastname': ['lll']}]

test_dict_f = {}

for d in test_dict:
    id_ = d.pop('id')
    test_dict_f[str(id_)] = d

print(test_dict_f)

输出:

{'0': {'name': ['Jim'], 'lastname': ['kkk']}, '1': {'name': ['John'], 'lastname': ['lll']}}

test_dict = [{'id': 0, 'name': ['Jim'], 'lastname': ['kkk']}, {'id': 1, 'name': ['John'], 'lastname': ['lll']}]


pp({i["id"]: {k:v for k,v in i.items() if k!="id"} for i in test_dict})
or event much funnier: 
pp({i["id"]: i|{"id":i["id"]} for i in test_dict})

{0: {'name': ['Jim'], 'lastname': ['kkk']},
 1: {'name': ['John'], 'lastname': ['lll']}}