Is it possible to give a python dict an initial capacity (and is it useful)

前端 未结 2 576
春和景丽
春和景丽 2021-01-04 01:36

I am filling a python dict with around 10,000,000 items. My understanding of dict (or hashtables) is that when too much elements get in them, the need to resize, an operatio

2条回答
  •  忘掉有多难
    2021-01-04 01:58

    Yes you can and here is a solution I found in another person's question that is related to yours too:

    d = {}
    for i in xrange(4000000):
    d[i] = None
    # 722ms
    
    d = dict(itertools.izip(xrange(4000000), itertools.repeat(None)))
    # 634ms
    
    dict.fromkeys(xrange(4000000))
    # 558ms
    
    s = set(xrange(4000000))
    dict.fromkeys(s)
    # Not including set construction 353ms
    

    those are different ways to initialize a dictionary with a certain size.

提交回复
热议问题