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

Turn List of Dictionaries into Dictionary of Dictionaries with index

I have a list of dictionaries, like this:

ls_dict = [{'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, 
{'A': 65, 'B': 66, 'C': 67}, 
{'a': 97, 'b': 98, 'c': 99}]

Which produces this:

[{'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, {'A': 65, 'B': 66, 'C': 67}, {'a': 97, 'b': 98, 'c': 99}]

What I want is a dictionary of dictionaries where each dictionary is indexed like the following:

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

{"0": {'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, "1": {'A': 65, 'B': 66, 'C': 67}, 2: {'a': 97, 'b': 98, 'c': 99}}

The additional problem is that I need to convert the former to the latter, rather than adapting my sample creation code, as I just spent 15 hours downloading the data into the current (wrong) format.

Any suggestions? Thank you.

>Solution :

You can do with enumerate,

In [75]: {str(index): lst for index, lst in enumerate(ls_dict)}
Out[75]: 
{'0': {'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'},
 '1': {'A': 65, 'B': 66, 'C': 67},
 '2': {'a': 97, 'b': 98, 'c': 99}}
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