471,310 Members | 1,400 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,310 software developers and data experts.

help on dictionary

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

Nov 1 '07 #1
1 988
On Nov 1, 11:21 pm, cesco <fd.calabr...@gmail.comwrote:
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))

--
Paul Hankin

Nov 1 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by dont bother | last post: by
4 posts views Thread by dont bother | last post: by
8 posts views Thread by rh0dium | last post: by
3 posts views Thread by aking | last post: by
6 posts views Thread by djm | last post: by
2 posts views Thread by hcaptech | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.