eugene
eugene

Reputation: 41665

Replacing an element in an OrderedDict?

Should I remove item at the index and add item at the index?

Where should I look at to find the source for OrderedDict class?

Upvotes: 0

Views: 4698

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

The OrderedDict uses the position of a value if it is already present; if it isn't, just treats it as a new value and adds it at the end.

This is in the documentation. If you need to replace and maintain order, you'll have to do it manually:

od = OrderedDict({i:i for i in range(4)})
# od = OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])

# Replace the key and value for key == 0:
d = OrderedDict(('replace','key') if key == 0 else (key, value) for key, value in od.items())
# d = OrderedDict([('replace', 'key'), (1, 1), (2, 2), (3, 3), (4, 4)])

# Single value replaces are done easily:
d[1] = 20  # and so on..

Additionally, at the top of the documentation page you'll see a reference to the file containing, among others, the source for the OrderedDict class. It is in collections.py and, actually, the first class defined.

Upvotes: 1

John Gordon
John Gordon

Reputation: 33335

From the Python documentation:

If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

Upvotes: 2

Related Questions