[dictionary] how to get key by item

Skip Montanaro skip at pobox.com
Tue Dec 14 04:09:34 CET 2004


    >> That doubles your storage, so you'll have to trade that off against
    >> the speed gain of not having to loop over the entire dictionary.

    Roy> Well, you *do* loop over the entire dictionary, but you only do it
    Roy> once, when you create the reverse dict.  If you are only going to
    Roy> do a single lookup, it's no gain, but if you amortize the cost over
    Roy> many lookups, it's almost certainly a big win.

Sure, but the OP said his dictionary was big.  It's up to him to decide
whether the space-time tradeoff is worth it (or even possible).

    Roy> BTW, does Python really build the intermediate list and throw it
    Roy> away after using it to initialize the dictionary, or is it smart
    Roy> enough to know that it doesn't really need to build the whole list
    Roy> in memory?

That's why I called .iteritems() in my example.  It won't generate the
entire list of tuples as .items() would.

Skip




More information about the Python-list mailing list