tikael tikael - 28 days ago 14
Python Question

Python 3.X write dictionary from list to file

I have a list like this:

d = [{string1:float1,string2: float2},{string1:float3,string2:float4},...]


I tried:

import json
with open("outputfile.txt","w") as f:
json.dump(d,f)


then all the content is in one line like:

[{string1:float1,string2: float2},{string1:float3,string2:float4},{string1:float5,string2:float6},...]


what I want is for each (key:valve) starts a newline,like

[{string1:float1,
string2:float2},
{string1:float3,
string2:float4},
...
endstring:endfloat}]


how can I do this ? or I can just replace every "," to ",\n"? The order does not matter much, but if possible, a "sorted" result will be appreciated.

Answer

As per https://docs.python.org/2.7/library/json.html:

json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))

should result in:

{
    "4": 5,
    "6": 7
}

Python 3.x solution is identical.

Note the use of dumps as opposed to dump.

Updated solution:

for dict in d:
    with open("outputfile.txt","a") as f:
        json.dump(dict, f)
        f.write('\n')

or

for dict in d:
    with open("outputfile.txt","a") as f:
        json.dump(dict, f, indent=4)
Comments