Skip to content

Instantly share code, notes, and snippets.

@void4
Last active October 26, 2017 23:41
Show Gist options
  • Save void4/c3d339c374be9e8f9c16f1105a19b856 to your computer and use it in GitHub Desktop.
Save void4/c3d339c374be9e8f9c16f1105a19b856 to your computer and use it in GitHub Desktop.
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)
@void4
Copy link
Author

void4 commented Oct 26, 2017

Python 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment