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.