×

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

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

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.