Put each object with same name into single dictionary python

I have following list of dictionaries:

[{'id': '1'},
 {'name': 'test'},
 {'email': 'test@gmail.com'},
 {'id': '2'},
 {'name': 'supra'},
 {'email': 'supra@gmail.com'},
 {'id': '3'},
 {'name': 'gtr'},
 {'email': 'gtr@gmail.com'}]

What i want is the following:

data_list = [{"id":"1", "name":"test", "email":"test@gmail.com"},
             {"id":"2", "name":"supra", "email":"supra@gmail.com"},
             ...]

What i have tried:

v = [{k: v for d in data_list for k, v in d.items()}]

But the above code updates only the last object cause of same key name.

Any idea how to solve this? Thank you.

>Solution :

Assuming the d is consistent, you can use the following (hacky) solution to iterate by the groups of 3:

ids = names = emails = iter(d)
data_list = [
    {
        'id': i['id'],
        'name': n['name'],
        'email': e['email']
    } for i, n, e in zip(ids, names, emails)
]

result:

[{'id': '1', 'name': 'test', 'email': 'test@gmail.com'}, {'id': '2', 'name': 'supra', 'email': 'supra@gmail.com'}, {'id': '3', 'name': 'gtr', 'email': 'gtr@gmail.com'}]

And even simpler (suggested by @fsimonjetz) and my favorite one:

ids = names = emails = iter(d)
data_list = [i | n | e for i, n, e in zip(ids, names, emails)]

Leave a Reply