Altering dictionaries/keys in Python
<p>I have ran the code below in Python to generate a list of words and their count from a text file. How would I go about filtering out words from my "frequency_list" variable that only have a count of 1? </p>

<p>In addition, how would I export the print statement loop at the bottom to a CSV</p>

<p>Thanks in advance for any help provided.</p>

<pre><code>import re
import string
frequency = {}
document_text = open('Words.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for word in match_pattern:
    count = frequency.get(word,0)
    frequency[word] = count + 1

frequency_list = frequency.keys()



for words in frequency_list:
    print (words, frequency[words])
</code></pre>

<p>To filter out words, an alternative way would be:</p>

<pre><code>frequency = dict(filter(lambda (k,v): v&gt;1, frequency.items())) 
</code></pre>

<p>To export the print statement loop at the bottom to a CSV, you could do that:</p>

<pre><code>import csv    
frequency_list = ['word1','word2','word3']  # example

with open('output.csv','w') as csvfile:
    writer = csv.writer(csvfile, delimiter=",")
    writer.writerow(frequency_list)
</code></pre>

<p>This will generate an 'output.csv' file with the words from your frequency_list in <em>one row</em>. </p>

<p>To get <em>a row for each word</em> try, the following:</p>

<pre><code>with open('output.csv','w') as csvfile:
    writer = csv.writer(csvfile, delimiter=",")
    writer.writerows([i.strip() for i in l.split(',')] for l in frequency_list)
</code></pre>

<blockquote>
  <p>Update</p>
</blockquote>

<p>To get a csv with the counters, keep your initial dictionary and do the following:</p>

<pre><code>frequency = {"one":1,"two":2,"three":3} #example
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    for key, value in frequency.items():
       writer.writerow([key, value])
</code></pre>

python dictionary export-to-csv