-1

I have a dictionary of the form:

data = {'a':'one','b':'two','c':'three'}

I want to convert this to a tab delimited text file such that the file reads as:

a    b    c    one    two    three.

I tried:

import json

data = {'a':'one','b':'two','c':'three'}

with open('file.txt', 'w') as file:
 file.write(json.dumps(data))

However the resulting file just reads as ('a':'one','b':'two','c':'three'). I knew it wouldn't be as simple as that, and I'm sure it's not complex, but I just can't seem to figure this one out.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Do you want all the keys *and* values in *one* row, as six columns? – inspectorG4dget Jan 10 '20 at 20:36
  • I suppose that the `csv` module should be used, setting delimiter to tab. – 9000 Jan 10 '20 at 20:40
  • @inspectorG4dget Yes, absolutely. Also, for learning purposes, if I was to have more than one dictionary, how could I create a text file so that the schema is the same but just on the proceeding row? – Ehsan Asif Jan 10 '20 at 20:41
  • If you wanted a tab delimited file, why did you use JSON? Also that's *not* what the file would look like. – jonrsharpe Jan 10 '20 at 20:44
  • Thanks @jonrsharpe, actually my data was imported from a json file, but I wanted to convert dictionary objects to string and one way to do it would be `json.dumps(data)`, I may be wrong, I'm pretty new to it. – Ehsan Asif Jan 10 '20 at 22:36

1 Answers1

-1
data = {'a':'one','b':'two','c':'three'}
s = ""
for x in data.keys():
  s += x
  s += "\t"
for x in data.values():
  s += x
  s += "\t"
print(s)

with open('file.txt', 'w') as file:
  file.write(s)

Dictionary is a structure that's designed for when a one-to-one association between values exist. Here is a link to further discussions on how it compares with other structures.

Therefore it makes sense to print the key:value pair together to preserve that association. Thus the default behaviour of print(data) or in your case file.write(data) when data is a dictionary is to output {'a': 'one', 'b': 'two', 'c': 'three'}.

The key1, key2, ... value1, value2 ... type of output format you request is not typical for a structure like dictionary, therefore a more "manual" approach like the one above involving two loops is required.

As for json, its usage is really not that relevant in the code you provided, maybe it is used in other parts of your code base when a json specific output format is required. You can read more on json here to know that it is a format independent of the python programming language.

B.Gao
  • 146
  • 1
  • 8
  • This may be obvious, but since I'm relatively new to Python it took me a minute, so just for learning purposes: often keys/values are not both strings and so can't be concatenated, in which case I used `s += str(x)` – Ehsan Asif Jan 10 '20 at 21:55
  • Added description in my answer that hopefully helps to clarify the issue. – B.Gao Jan 11 '20 at 18:17