You can just create a helper method that inserts the elements into a nested dictionary one at a time, each time checking to see if the desired sub-dictionary already exists or not:
dict = {}
def insert(fourgram):
d = dict # reference
for el in fourgram[0:-1]: # elements 1-3 if fourgram has 4 elements
if el not in d: d[el] = {} # create new, empty dict
d = d[el] # move into next level dict
if fourgram[-1] in d: d[fourgram[-1]] += 1 # increment existing, or...
else: d[fourgram[-1]] = 1 # ...create as 1 first time
You can populate it with your dataset like:
insert(['I','go','to','work'])
insert(['I','go','there','often'])
insert(['it','is','nice','being'])
insert(['I','live','in','NY'])
insert(['I','go','to','work'])
after which, you can index into dict
as desired:
print( dict['I']['go']['to']['work'] ); # prints 2
print( dict['I']['go']['there']['often'] ); # prints 1
print( dict['it']['is']['nice']['being'] ); # prints 1
print( dict['I']['live']['in']['NY'] ); # prints 1