Skip to content

Instantly share code, notes, and snippets.

@treygriffith
Created October 18, 2014 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treygriffith/6bd361731790776678c2 to your computer and use it in GitHub Desktop.
Save treygriffith/6bd361731790776678c2 to your computer and use it in GitHub Desktop.
An Immutable Dictionary in python - a tuple with real keys
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])
@treygriffith
Copy link
Author

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:

coordinates = ImmutableDict({x: 123, y: 136})
print coordinates["x"] # 123

Feels better to me than:

coordinates = (123, 136)
print coordinates[0] # 123

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!

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