简体   繁体   中英

Writing list of dictionaries in a text file with python

I have a list of dictionaries that I want to write in a text file, each dictionary as a line in that text file such that each line start with 1 and then the dictionary as follow:

    1 47:1 1365:1 250:1 1511:1 112:1 44:2 246:1 158:1 1588:1 69:2 24:3 
    1 500:1 365:1 399:1 14:1 428:1 1083:2 1957:2 5:1 71:1 68:1 95:1

How to do this in python without '{' or ','?

You can do it like that:

dictList = [{'47':1, '1365':1, '250':1, '1511':1, '112':1, '44':2, '246':1, '158':1, '1588':1, '69':2, '24':3},{'500':1, '365':1, '399':1, '14':1, '428':1, '1083':2, '1957':2, '5':1, '71':1, '68':1, '95':1}]

with open('output.txt', 'w') as outFile:
    for d in dictList:
        line =  "1 " + " ".join([str(key)+':'+str(value) for key,value in d.items()]) + '\n'
        outFile.write(line)

Output of file:

1 47:1 1365:1 250:1 1511:1 112:1 44:2 246:1 158:1 1588:1 69:2 24:3
1 500:1 365:1 399:1 14:1 428:1 1083:2 1957:2 5:1 71:1 68:1 95:1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM