1

I have a dictionary like this: `

d = {1: array([ 1.,  1., 0., 1.]),2: array([ 0.,  1., 0., 1.]), 3:
        array([ 1.,  0., 0., 1.]), 4: array([ 1.,  0., 1., 1.])}`

I want to write all the values:

 ([ 1.,  1., 0., 1.], [ 0.,  1., 0., 1.], 
  [ 1.,  0., 0., 1.], [ 1.,  0., 1., 1.]) 

in a .tsv file. Each value in a column, in this example I would have 4 columns with 4 rows.

This is what I want in the file:

1 0 1 1

1 1 0 0

0 0 0 1

1 1 1 1

each numpy array is printed in a different column.

The code that I have gives me all values in the same column:

f = open("Result.tsv", "wb")
for key, value in d.items():
    np.savetxt(f, value, delimiter=',')
f.close()
2
  • Please don't mask the built in dict with your own. I changed the variable name to d Commented Dec 10, 2015 at 11:10
  • Thank you! I'm new at this. Commented Dec 10, 2015 at 15:35

2 Answers 2

1

Simplest way might be to format your array to be 2d rather than a dict of 1d columns:

out = np.empty((4, 4))
for colnb, col in d.items():
    out[:, colnb-1] = col
with open("Result.tsv", 'wb') as f:
    np.savetxt(f, out, delimiter=',')

This way, you let the numpy savetxt function handle all the work

Sign up to request clarification or add additional context in comments.

2 Comments

This code throws an exception IndexError: index 4 is out of bounds for axis 1 with size 4
@Oz123: You're absolutely right: I forgot the 0-indexing. Corrected it now (although this is more to give an idea than anything ressembling a robust implementation). Thank you !
0

This gives you almost what you wanted:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        f.write(str(v)[1:-1]+'\n')



$ cat Result.csv
 1.  1.  0.  1.
 0.  1.  0.  1.
 1.  0.  0.  1.
 1.  0.  1.  1.

This goes the extra step and removes the decimal point:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        f.write(str(map(int, v))[1:-1]+'\n')

Note also that if you are already writing this as a binary file, which is input for another program you can do the following (but this does not give you the text format you showed). And finally you do this:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        v.tofile(f, sep=',', format='%d')
        f.write('\n')       

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.