How to get the number of keys in a dictionary in python ?

Published: August 06, 2021

Tags: Python; Dictionary; Size;

DMCA.com Protection Status

Example of how to get the number of keys in a dictionary in python:

Create a dictionary in python

Lets first create a simple dictionary:

d = {'a':1,'b':2,'c':3,'d':4,'e':5}

Get the number of keys in a dictionary

To get the number of keys, a straightforward solution it to use len():

 len(d)

returns

 5

or

len(d.keys())

also returns

    5

Example of use

Let's assume a dictionary with unknown size:

d = {}

for i in range(1000000):
    d[i] = random.randint(1,10)

The goal is to print only the first 100 keys if the size is greater than 100:

from itertools import islice

    if len(d) > 100:
        for item in islice(d.items(), 100):
                print('Key:{} Value:{}'.format(item[0], item[1]))

returns

Key:0 Value:1
Key:1 Value:7
Key:2 Value:10
Key:3 Value:7
Key:4 Value:8

References