Created
October 4, 2018 04:53
-
-
Save theY4Kman/455bb6040a8910a3cdb6060e106c37b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
from contextlib import contextmanager | |
@contextmanager | |
def preserve_dict_order(d: OrderedDict): | |
"""Allow mutations on an OrderedDict, restoring its original order after | |
""" | |
original_order = list(d) | |
yield d | |
old_keys = set(original_order) | |
added_keys = [k for k in d if k not in old_keys] | |
new_order = original_order + added_keys | |
for key in new_order: | |
if key in d: | |
d[key] = d[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment