Home > other >  How to "flatten" list of dictionaries in python
How to "flatten" list of dictionaries in python

Time:05-17

I have a list of dictionaries that looks like this:

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']}]

I would like to create another dictionary that will have as keys, the ids of the test_dict.

The output I am looking for, looks like this:

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']}}

Any ideas how I could achieve this ?

CodePudding user response:

Try this in one line:

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

the result will be:

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

CodePudding user response:

Here's another way to do it that doesn't rely on knowledge of any keys other than 'id'. Note that this is destructive:

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)

Output:

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

CodePudding user response:


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']}}
  • Related