How to save a dictionary to a file with key values ​​one per line?

I want the text to be one key: the number per line. Right now, it saves the file as a simple dictionary, and I cannot figure it out.

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
+4
source share
3 answers

You can do this a couple of lines with CounterDict and the csv module:

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())

Using two dictionaries is pointless if you just want to save key / value pairs. A single counter will receive a counter for all words, and csv.writerows will record each pair separated by a colon, one in each line.

+3
source

try it

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

EDIT: since iteritems is being removed from python 3, change the code to items ()

+2
source

// Very simple dictionary for printing files

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)
0
source

All Articles