×

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count, including count values, count keys, duplicate count values, count key and value occurrences, and creating a python dictionary with the count.

Python dictionary count

Dictionary count means to have a count of keys and values in a python dictionary. We use a function called len() through which we can count the number of key and value pairs of a dictionary.

If we need the count of key-value pairs, we use the len() function. For example, let us have a look at this code

Example

dict={"apple":5, "bananas":4, "orange":6, "grapes":10, "mango":3}
count=len(dict)
print("the count of this dictionary is:",count)

Output

The count of this dictionary is: 5

In the above code, we created a dictionary of the name dict and have a few keys and their assigned values. To find the count of keys-values of that dictionary, we used the len() function. Once the code is executed, we get a count of key-value pairs presented in that dictionary, giving the count of ‘5’,

Count only dictionary values

You can count only values in a python dictionary using the same len() function, but as this function gives number of pairs, you need a count of only values. Now we use dict.values() method to extract only values from the dictionary. This function is an inbuilt function that is available in the python package.

Example

dict={"apple":5, "bananas":4, "orange":6, "grapes":10, "mango":3}
count=len(dict.values())
print("the count of values in this dictionary is:",count)

Output

the count of values in this dictionary is: 5

In this code, we see a dictionary with the name dict. Here, we are counting only values of that dict by using the function len() and dict.values() method. As the code executes, we get the value count as 5. 

Count duplicate values from the dictionary

Here well, see how to count the duplicate values in the python dictionary. So to get the duplicate value count, we use the Counter() method to count the duplicate values in the dictionary.

Example

From collections import Counter


dict={"apple":5, "bananas":3, "orange":5, "grapes":10, "mango":3, "Leche":2}
count=Counter(dict.values())
print("the count of duplicate values in this dictionary are:",count)

output

the count of duplicate values in this dictionary are: Counter({5: 2, 3: 2, 10: 1, 2: 1})

In the code, we created a dictionary name dict and assigned some key-values to it. As we wanted to count the duplicate values, we first imported Counter from collections and then used the command Counter() with dict.values() and printed the output. As the program executes, we get the output of the values and the times it got repeated.

Counting key occurrences in the dictionary

To count the key occurrences in the dictionary, we use Counter () by importing it from collections and chain()  by importing it from itertools methods. As we create a dictionary and use these functions. Let us look at an example:

from collections import Counter
from itertools import chain
dict={"apple":5, "bananas":3, "orange":5, "grapes":10, "mango":3, "leche":2}
count=Counter(chain.from_iterable(dict))
print("the count of key occurrences in this dictionary are:",count)

Output:

the count of key occurrences in this dictionary are: Counter({'a': 7, 'e': 5, 'n': 4, 'p': 3, 'g': 3, 'l': 2, 's': 2, 'o': 2, 'r': 2, 'b': 1, 'm': 1, 'c': 1, 'h': 1})

As you can see in the above code, we created a dictionary of name dict with key-values. To count the number of key occurrences, we used the method Counter() and chain() and got the output of all the key occurrences in that dictionary.

Creating a dictionary using count

Here we will see how to create a dictionary using count in python. So to create the dictionary, we have to create a list and assign some elements. And then, we create a variable and use the list comprehension method to use the values from the list. Let us look at an example:

listA = ['apple','apple','mango','mango','orange','orange','orange']


new_list = {m:listA.count(m) for m in listA}
print(new_list)

Output

{'apple': 2, 'mango': 2, 'orange': 3}

Looking at this code, we created a list and appended values to it, then made a new list, used the comprehension method, and printed the new list. After execution, we can find a new dictionary created by the value occurrence from the list.


Related Topics

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Amazon rekognition using python

Amazon recognition service is an AI service which is an image labelling API (Application programming interface). In this article, we shall learn to use the AWS python boto3 module to...

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.