help on dictionary

Paul Hankin paul.hankin at gmail.com
Fri Nov 2 00:47:09 CET 2007


On Nov 1, 11:21 pm, cesco <fd.calabr... at gmail.com> wrote:
> 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




More information about the Python-list mailing list