简体   繁体   English

用python在文本文件中写入字典列表

[英]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 开头,然后字典如下:

    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 ','?如何在没有“{”或“,”的情况下在python中执行此操作?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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