Python's simplicity philosophy

Andrew Dalke adalke at mindspring.com
Thu Nov 20 06:02:58 CET 2003


Me:
> > And I've used what can now be written as
> >
> >   unique_keys = dict.from_keys(lst).keys()

Paul Rubin:
> This from_keys operation must be something new, and consing up a
> dictionary like that is a woeful amount of overhead.  But I guess
> it would do the job.

Hmm, I misspelled it -- should be 'fromkeys' without the underscore.
Got confused with 'has_key'....

It's a new class method for dict

fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.

I said 'what can now be written as' meaning that before the
class method I would write it as

d = {}
for x in lst:
  d[x] = 1
unique_keys = d.keys()

I don't know what you mean by 'consing up a dictionary'
taking up a 'woeful amount of overhead'.  It's a bit of overhead,
but not woefully so.  (And what does 'consing' mean?  It's
a Lisp thing, yes?  A 'cons cell' is the first / rest pair?)

BTW, another option is

  unique_keys = list(sets.Set(lst))

but I still haven't internalized the sets module enough to
remember it trippingly.

For the case where I want a list of unique keys and where
I don't care about the resulting order then either of these
should work nicely.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list