Counting the number of distinct keys in a dictionary in Python Counting the number of distinct keys in a dictionary in Python python python

Counting the number of distinct keys in a dictionary in Python


len(yourdict.keys())

or just

len(yourdict)

If you like to count unique words in the file, you could just use set and do like

len(set(open(yourdictfile).read().split()))


The number of distinct words (i.e. count of entries in the dictionary) can be found using the len() function.

> a = {'foo':42, 'bar':69}> len(a)2

To get all the distinct words (i.e. the keys), use the .keys() method.

> list(a.keys())['foo', 'bar']


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)# 1000len(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)