Counting the Number of keywords in a dictionary in python

前端 未结 5 1573
离开以前
离开以前 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:48

    Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.

    System specs:

    • python =3.7.4,
    • conda = 4.8.0
    • 3.6Ghz, 8 core, 16gb.
    import timeit
    
    d = {x: x**2 for x in range(1000)}
    #print (d)
    print (len(d))
    # 1000
    
    print (len(d.keys()))
    # 1000
    
    print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1
    
    print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2
    

    Result:

    1) = 37.0100378

    2) = 37.002148899999995

    So it seems that len(d.keys()) is currently faster than just using len().

提交回复
热议问题