Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 694
Skamah One Avatar asked Mar 20 '15 01:03

Skamah One


People also ask

Does Python dictionary preserve order?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

What is an OrderedDict?

An OrderedDict is a dictionary subclass in which the order of the content added is maintained.

Are dictionary Keys ordered Python?

Python 3.6 (CPython) As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default.


1 Answers

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.

like image 116
humanoid Avatar answered Sep 24 '22 21:09

humanoid