-1

So i'm having serval data store in python dictionary, and I wanted to put them into one .txt file. Does anyone know how i can do that?

Example:

dict={'a': array([1,2,3]), 'b': array([10,11,12]), 'c': array([20,21,22])}

desired output in txt file:

a ,b  ,c
1 ,10 ,20
2 ,11 ,21
3 ,12 ,22

Please let me know, really appreciate your help .

I've try using the for loop and the json file type, but still couldn't figure out. I'm new here, so please let me know if need more info, thanks.

2 Answers2

1

I think you will find this answer to a similar question helpful. The idea is simply to serialize the dictionary to a JSON string, then store that string in a file.

More succinctly:

import json

mydict = {'a': [0, 1], 'b': [2, 7]}

with open('myfile.json', 'w') as f:
  json.dump(mydict, f)
Jeff
  • 856
  • 7
  • 13
  • 1
    Where is the conversion to JSON?: – user19077881 Aug 30 '23 at 19:47
  • @user19077881 yeah sorry I screwed up when copy-pasting my code into my original answer. fixed it with an edit just now to use `json.dump` instead of `f.write` – Jeff Aug 30 '23 at 19:49
  • 1
    This will not work with numpy arrays - `TypeError: Object of type ndarray is not JSON serializable` – Chris Charley Aug 30 '23 at 20:04
  • @ChrisCharley Agreed. If you're working with numpy data you would probably want to look up [pandas.DataFrame.to_csv](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html#pandas-dataframe-to-csv). Or write your own encoder to serialize the data like [this](https://stackoverflow.com/a/47626762/5905029). – Jeff Aug 30 '23 at 20:10
0

Try something like this, I'm using pandas here to dump to txt file but you can use it to dump as a csv file as well:

from numpy import array
dict_ = {'a': array([1,2,3]), 'b': array([10,11,12]), 'c': array([20,21,22])}
import pandas as pd

path = r"abc.txt"
with open(path, 'a') as f:
    df_ = pd.DataFrame(dict_).to_string(header=True, index=False)
    f.write(df_)

To dump into a csv instead just use pd.to_csv

Suraj Shourie
  • 536
  • 2
  • 11
  • Thank you for the answer. Also, what if i have different length of the array? Is there any way that I can still save them regardless the length of the array? ValueError: All arrays must be of the same length – Kenneth Su Aug 30 '23 at 20:14
  • See this question for how to do [that](https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths) – Suraj Shourie Aug 30 '23 at 20:53
  • How can i read them back tho? with the same array instead of the string? Really appreciate your help. – Kenneth Su Aug 31 '23 at 22:30