Created
October 18, 2014 18:44
-
-
Save treygriffith/6bd361731790776678c2 to your computer and use it in GitHub Desktop.
An Immutable Dictionary in python - a tuple with real keys
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
class ImmutableDict: | |
"""A tuple with non-index keys""" | |
def __init__(self, dict): | |
self._keys = tuple(dict.keys()) | |
self._values = tuple(dict.values()) | |
def __len__(self): | |
return len(self._keys) | |
def __getitem__(self, key): | |
return self._values[self._keys.index(key)] | |
def __iter__(self): | |
for key in self._keys: | |
yield key | |
def __contains__(self, value): | |
return value in self._values | |
def keys(self): | |
return list(self._keys) | |
def values(self): | |
return list(self._values) | |
def items(self): | |
return zip(self._keys, self._values) | |
def has_key(self, key): | |
return key in self._keys | |
def get(self, key, default=None): | |
if key in self._keys: | |
return self[key] | |
else: | |
return default | |
def iterkeys(self): | |
for key in self: | |
yield key | |
def itervalues(self): | |
for value in self._values: | |
yield value | |
def iteritems(self): | |
for key in self: | |
yield (key, self[key]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't write python, but I thought of this after looking into the differences between tuples and lists and dictionaries in python.
It seems to me that for a lot of the uses of tuples, an immutable dictionary would actually be better.
For example, for coordinates:
Feels better to me than:
Especially for more complicated coordinate systems (i.e. ones where the ordering is not necessarily universally understood).
Since I'm a python newbie, this might be totally off-base, but it was fun learning about the different data structures in Python!