Search code examples
pythonpython-3.xordereddictionary

Update OrderedDict's value at position?


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

Solution

  • 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.