Home > Enterprise >  How to change index values of a dict?
How to change index values of a dict?

Time:04-08

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:

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?

CodePudding user response:

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

for i, value in enumerate(dct.values(), start=1):
    value['index'] = i
  • Related