Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading