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

How to change index values of a dict?

Is it possible to change the values of a sorted dictionary?

After sorting the dict alphabetically I got a result like this:

OrderedDict([('a', {'index': 3, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 4, 'parent': 'a/b'}),
             ('a/b/d', {'index': 1, 'parent': 'a/b'})])

This dict has a bunch more of key/value pairs like that, my expected output is to maintain it sorted alphabetically but change the indexes value so it looks like this:

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

OrderedDict([('a', {'index': 1, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 3, 'parent': 'a/b'}),
             ('a/b/d', {'index': 4, 'parent': 'a/b'})])

How can I do that?

>Solution :

Iterate over the dictionary’s values and set each value’s index:

for i, value in enumerate(dct.values(), start=1):
    value['index'] = i
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