MedaUser
MedaUser

Reputation: 133

Creating list of objects from a dictionary

This takes in a dictionary(words)... note that this is an example, the dictionary can vary in size:

{'wandered': [YearCount( year=2005, count=83769 ), YearCount( year=2006, count=87688 ), YearCount( year=2007, count=108634 ), YearCount( year=2008, count=171015 )], 'request': [YearCount( year=2005, count=646179 ), YearCount( year=2006, count=677820 ), YearCount( year=2007, count=697645 ), YearCount( year=2008, count=795265 )], 'airport': [YearCount( year=2007, count=175702 ), YearCount( year=2008, count=173294 )]}

And then my function returns A list of WordCount objects in sorted order from least frequent to highest:

def wordFrequencies(words):
    count = []   
    for item, val in words.items():
        for i in val:
            wc = createWordCount(str(item), int(i.count))
            count.append(wc)
    newcount = count
    newcount.sort(key = lambda x: x.count)
    print(newcount)

Output:

[WordCount( word='wandered', count=83769 ), WordCount( word='wandered', count=87688 ), WordCount( word='wandered', count=108634 ), WordCount( word='wandered', count=171015 ), WordCount( word='airport', count=173294 ), WordCount( word='airport', count=175702 ), WordCount( word='request', count=646179 ), WordCount( word='request', count=677820 ), WordCount( word='request', count=697645 ), WordCount( word='request', count=795265 )]

But what I need is A list of WordCount objects in decreasing order from most to least frequent that adds the previous count each time to the previous object instead of just adding in a new object,it should look like this:

[WordCount( word=’request’, count=2816909 ),
WordCount( word=’wandered’, count=451106 ),
WordCount( word=’airport’, count=348996 )]

Upvotes: 0

Views: 98

Answers (1)

Eyal Ch
Eyal Ch

Reputation: 10056

def wordFrequencies(words):
    count = []   
    for item, val in words.items():
        c = 0
        for i in val:
            c+=int(i.count)
        wc = createWordCount(str(item), c)
        count.append(wc)
    newcount = count
    newcount.sort(key = lambda x: x.count,reverse=True)
    print(newcount)

Upvotes: 1

Related Questions