Counting the Number of keywords in a dictionary in python

前端 未结 5 1532
离开以前
离开以前 2020-12-04 08:11

I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so I wanted to count the number of keywords. I

5条回答
  •  独厮守ぢ
    2020-12-04 08:43

    Calling len() directly on your dictionary works, and is faster than building an iterator, d.keys(), and calling len() on it, but the speed of either will negligible in comparison to whatever else your program is doing.

    d = {x: x**2 for x in range(1000)}
    
    len(d)
    # 1000
    
    len(d.keys())
    # 1000
    
    %timeit len(d)
    # 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    
    %timeit len(d.keys())
    # 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    

提交回复
热议问题