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

Active August 06, 2021    /    Viewed 425    /    Comments 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount