MedaUser
MedaUser

Reputation: 133

A dictionary mapping words to lists of objects

Here's my code so far: *rit_object is a a private class that assigns types for each parameter

from rit_object import *

class YearCount(rit_object):
    __slots__ = ( 'year', 'count')
    _types = (int, int)

def createYearCount(year, count):
    return YearCount(year, count)

def readWordFile(fileName):
    #read in the entire unigram dataset
    for line in fileName:
        new = line.split(', ')
        print(new)
        #s = createYearCount(int(line[1]), line[2])
        #print(s)


def main():
    fileName = input('Enter filename: ')
    readWordFile(open(fileName))

main()

I have to read in a csv file which represents a word, the year, and the occurrences of that word in that year:

airport, 2007, 175702
airport, 2008, 173294
request, 2005, 646179
request, 2006, 677820
request, 2007, 697645
request, 2008, 795265
wandered, 2005, 83769
wandered, 2006, 87688
wandered, 2007, 108634
wandered, 2008, 171015

My readWordFile function should input a fileName and output a dictionary mapping words to lists of YearCount object. the output should look like:

{’airport’: [YearCount( year=2007, count=175702 ), YearCount( year=2008,
count=173294 )], ’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 )]}

I'm not sure how to use dictionary mapping. How do I create the dictionary containing a the word as they key and the value is the YearCount object containing the year and count.?

Upvotes: 0

Views: 200

Answers (1)

Yang Yuan
Yang Yuan

Reputation: 176

first you should have a dict obj

result = {}

then, in function readWordFile

new = line.split(', ')
id = new[0]
yc = createYearCount(int(new[1]), new[2])
# add to list or create a new list
if (not result.has_key(id)):
        result[id] = [yc]
    else:
        result[id].append(yc)

Upvotes: 1

Related Questions