Last active
October 26, 2017 23:41
-
-
Save void4/c3d339c374be9e8f9c16f1105a19b856 to your computer and use it in GitHub Desktop.
This file contains 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 | |
# Allows for dot dict access, but is also ordered (but not nested yet) | |
# Evil hack 1 from | |
#https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary | |
class OrderedAttributeDict(OrderedDict): | |
__getattr__ = dict.__getitem__ | |
__setattr__ = dict.__setitem__ | |
__delattr__ = dict.__delitem__ | |
# Allows to create ordered dicts with simple syntax | |
# Evil hack 2 from | |
#https://stackoverflow.com/questions/7878933/override-the-notation-so-i-get-an-ordereddict-instead-of-a-dict | |
class _OrderedDictMaker(object): | |
def __getitem__(self, keys): | |
if not isinstance(keys, tuple): | |
keys = (keys,) | |
assert all(isinstance(key, slice) for key in keys) | |
return OrderedAttributeDict([(k.start, k.stop) for k in keys]) | |
odict = _OrderedDictMaker() | |
dictionary = odict[ | |
"all": "of", | |
"these":"keys", | |
"are":"ordered" | |
] | |
print(dictionary) | |
# and you can access attributes like this: | |
print(dictionary.these) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python 3