Efficient way to remove keys with empty strings from a dict

前端 未结 17 1272

I have a dict and would like to remove all the keys for which there are empty value strings.

metadata = {u\'Composite:PreviewImage\': u\'(Binary data 101973          


        
17条回答
  •  心在旅途
    2020-11-27 13:17

    Some benchmarking:

    1. List comprehension recreate dict

    In [7]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
       ...: dic = {k: v for k, v in dic.items() if v is not None} 
       1000000 loops, best of 7: 375 ns per loop
    

    2. List comprehension recreate dict using dict()

    In [8]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
       ...: dic = dict((k, v) for k, v in dic.items() if v is not None)
    1000000 loops, best of 7: 681 ns per loop
    

    3. Loop and delete key if v is None

    In [10]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
        ...: for k, v in dic.items():
        ...:   if v is None:
        ...:     del dic[k]
        ...: 
    10000000 loops, best of 7: 160 ns per loop
    

    so loop and delete is the fastest at 160ns, list comprehension is half as slow at ~375ns and with a call to dict() is half as slow again ~680ns.

    Wrapping 3 into a function brings it back down again to about 275ns. Also for me PyPy was about twice as fast as neet python.

提交回复
热议问题