help on dictionary

C

cesco

Hi,

I have a defaultdict which I have initialized as follows:

def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model

def_dict = train(large_set_of_words)

where large_set_of_words is the list of possible strings.

I'd like to use such a default_dict as follows:

return max(list_of_strings, key=lambda w: dic[w])

that is, among the strings in list_of_strings, I'd like to return the
one with the highest score in def_dict.

The problem with such approach is that if the list_of_strings contains
a string that is not part of the def_dict, such a string gets added to
it while I'd like to keep the original def_dict unchanged/frozen.

Do you have any suggestion on how to do that?

Thanks and regards
Francesco

P.S. the code above is part from Norvig's spelling corrector
 
P

Paul Hankin

Hi,

I have a defaultdict which I have initialized as follows:

def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model

def_dict = train(large_set_of_words)

where large_set_of_words is the list of possible strings.

I'd like to use such a default_dict as follows:

return max(list_of_strings, key=lambda w: dic[w])

that is, among the strings in list_of_strings, I'd like to return the
one with the highest score in def_dict.

The problem with such approach is that if the list_of_strings contains
a string that is not part of the def_dict, such a string gets added to
it while I'd like to keep the original def_dict unchanged/frozen.

Do you have any suggestion on how to do that?

Use .get instead of [], and use sensible variable names:
return max(words, key=lambda word: model.get(word, 1))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top