The problem with the generalization is that the diagonal ones are not unique. So you will have to decide how you are going to do that on your own. As far as the other matrices are concerned the code should not be very difficult. The most efficient way of doing it is to start with the raising and lowering operators i.e. symmetric matrices which have a single one in the off-diagonal element. The transpose of that would be the lowering operator. The just the combinations \sigma_{+} \pm i \sigma_{-} gives you all the off-diagonal elements.