@classmethod
def from_dict(cls, D):
    """
        Build a matrix from a dictionary from indexes to values.
        """
    N, M = cls.shape
    data = [0] * (N * M)
    for (i, j), value in D.items():
        if i >= cls.nrows or j >= cls.nrows:
            fmt = N, M, (i, j)
            raise IndexError('invalid index for %sx%s matrix: %r' % fmt)
        k = i * N + j
        data[k] = value
    return cls.from_flat(data)
