Python: List vs Dict for look up table

后端 未结 8 896
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 10:41

I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a list or dict?

I know

8条回答
  •  孤街浪徒
    2020-11-22 10:58

    Speed

    Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.

    Memory

    Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.

    If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.

提交回复
热议问题