[Numpy-discussion] Making NpzFiles behave more like dictionaries.

David Warde-Farley dwf at cs.toronto.edu
Tue Jun 2 14:55:02 EDT 2009


It's occasionally annoyed me that NpzFiles can't be swapped in  
transparently for an in-memory dictionary since getting at the keys  
requires an attribute access. Below is a patch that implements some  
more of the dictionary interface for the NpzFile class. Any comments  
as to whether this is a good/bad idea, or about the specific  



Index: io.py
--- io.py       (revision 7031)
+++ io.py       (working copy)
@@ -118,6 +118,25 @@
              raise KeyError, "%s is not a file in the archive" % key

+    def __iter__(self):
+        return iter(self.files)
+    def items(self):
+        return [(f, self[f]) for f in self.files]
+    def iteritems(self):
+        return ((f, self[f]) for f in self.files)
+    def keys(self):
+        return self.files
+    def iterkeys(self):
+        return self.__iter__()
+    def __contains__(self, key):
+        return self.files.__contains__(key)
  def load(file, mmap_mode=None):
      Load a pickled, ``.npy``, or ``.npz`` binary file.

More information about the NumPy-Discussion mailing list