如何将字典保存到每行一个键值的文件中?

时间:2015-06-05 23:38:30

标签: python dictionary

我希望文本是一个键:每行计数。 现在它将文件保存为普通字典,我无法弄明白。

def makeFile(textSorted, newFile) :
dictionary = {}
counts = {}
for word in textSorted :
    dictionary[word] = counts
    counts[word] = counts.get(word, 0) + 1

# Save it to a file
with open(newFile, "w") as file :
    file.write(str(counts))
file.close()
return counts

3 个答案:

答案 0 :(得分:3)

你可以这样使用CounterDict和csv模块:

import csv
def makeFile(textSorted, newFile) :
    from collections import Counter
    with open(newFile, "w") as f:
        wr = csv.writer(f,delimiter=":")
        wr.writerows(Counter(textSorted).items())

如果您只想存储键/值对,则使用两个词典毫无意义。单个Counter dict将获得所有单词的计数,csv.writerows将每行写入一对冒号分隔。

答案 1 :(得分:2)

试试这个

def makeFile(textSorted, newFile) :
    counts = {}
    for word in textSorted :
        counts[word] = counts.get(word, 0) + 1

    # Save it to a file
    with open(newFile, "w") as file :
        for key,value in counts.items():
            file.write("%s:%s\n" % (key,value))
    return counts

编辑:因为从python 3中删除了iteritems,所以将代码更改为items()

答案 2 :(得分:0)

//非常基本的文件打印机字典

dictionary = {"first": "Hello", "second": "World!"}

with open("file_name.txt", "w") as file:

  for k, v in dictionary.items():

    dictionary_content = k + ": " + v + "\n"

    file.write(dictionary_content)