Update OrderedDict's value at position?

Skamah One picture Skamah One · Mar 20, 2015 · Viewed 14.1k times · Source

How would I update OrderedDict's values at certain position (beginning from 0)? So:

od = OrderedDict(a=1, b=2, c=3)
od.update({'b': 4}) # a=1, b=4, c=3
od.update_values(2, 1)  # a=2, b=1, c=3

Answer

humanoid picture humanoid · Mar 20, 2015

This is simple - just use od[od.keys()[x]] = y

This works for dictionaries too (although that would be pointless.) The code simply takes a list of the keys of the orderedDict, then takes the entry at the desired position from the list, and then uses that string as a key for the original orderedDict.