how to write add frequency in particular file by reading a csv file and then making a new file of multiple csv file by adding frequency

Jerry Hill malaclypse2 at gmail.com
Tue Jun 27 16:06:49 EDT 2017


On Fri, Jun 23, 2017 at 4:07 PM, Mark Byrne <mbyrnepr2 at gmail.com> wrote:

> Possible fix is to replace this:
>
> count = frequency.get(word,0)
> count1 = frequency.get(word1,0)
> if word1 == word:
>     frequency[word] = count + count1
> else:
>     frequency[word] = count
>
> with this:
>
> if word1 == word:
>     if word in frequency:
>         frequency[word] += 1
>     else:
>         frequency[word] = 1
>

Have you considered replacing your frequency dict with a
defaultdict(int)​?  That way you could boil the whole thing down to:

from collections import defaultdict
frequency = defaultdict(int)
...
<more code here>
...
if word1 == word:
    frequency[word] += 1

The defaultdict takes care of the special case for you.  If the value is
missing, it's defaulted to 0.

-- 
Jerry



More information about the Python-list mailing list