Count dict items python

Python dictionary length – Everything you need to know

This Python tutorial will discuss how to use and find Python dictionary length.

There are 5 ways to find the length of a dictionary in Python, which is shown below:

  • Using the len() function
  • Using the len() function with keys() method
  • Using the len() function with values() method
  • Using recursion
  • Using the dictionary comprehension

How to find Python dictionary length

Here we will discuss 5 different methods to find the length of a dictionary in Python. And we will start with the basic method of using len() function.

Method-1: Using the len() function

This method is the most straightforward way to find the length of a dictionary in Python. The built-in len() function can be used to return the number of key-value pairs in the dictionary. It works by taking the dictionary as an argument and returning its length.

# Create a dictionary called "my_dict" with three key-value pairs my_dict = # Print the length of the dictionary to the console print("Length of dictionary:",len(my_dict))

The above code creates a dictionary called my_dict that contains three key-value pairs where each key is a name and each value is an age.

  • It then prints the length of the dictionary to the console using the len() function.
Читайте также:  Php xmlwriter extension missing

Python dictionary length

Method-2: Using the len() function with keys() method

This method is a variation of the first method, but instead of passing the entire dictionary to the len() function, we use the keys() method of the dictionary to get a list of all the keys and then pass it to the len() function. This returns the number of keys in the dictionary, which is equal to the number of key-value pairs.

# Create a dictionary called "my_dict" with three key-value pairs my_dict = # Get the keys of the dictionary using the keys() method, get its length using len(), and print it to the console print(len(my_dict.keys())) 

The above code creates a dictionary called my_dict that contains three key-value pairs. It then uses the keys() method to get a list-like object containing the keys of the dictionary, and then prints the length of that object to the console using the len() function.

Method-3: Using the len() function with values() method

This method is similar to Method 2, but instead of using the keys() method, we use the values() method of the dictionary to get a list of all the values and then pass it to the len() function. This returns the number of values in the dictionary, which is again equal to the number of key-value pairs.

# Create a dictionary called "my_dict" with three key-value pairs my_dict = # Get the keys of the dictionary using the values() method, get its length using len(), and print it to the console print(len(my_dict.values()))

The code creates a dictionary called my_dict with three key-value pairs.

  • It then tries to get the length of the dictionary values by using the values () method and prints the length to the console.

Method-4 Using recursion

To find the length of a dictionary using recursion, we can define a function that recursively counts the number of key-value pairs in the dictionary.

# Define a recursive function that takes a dictionary as input and counts the total number of key-value pairs def count_dict(d): count = 0 # Iterate through each key-value pair in the dictionary for k, v in d.items(): count += 1 # Increment the count by 1 for each key-value pair # If the value is itself a dictionary, recursively call the function to count its key-value pairs if isinstance(v, dict): count += count_dict(v) # Return the total count of key-value pairs in the dictionary return count # Create a dictionary called "my_dict" my_dict = # Call the count_dict function with my_dict as the input and print the total count to the console print(count_dict(my_dict))

The above code defines a function called count_dict that takes a dictionary as input and recursively counts the number of keys in the dictionary.

  • The function iterates over the key-value pairs of the input dictionary, increments the counter for each key, and recursively calls itself if the value of a key is also a dictionary.
  • The code then creates a dictionary my_dict and calls the count_dict function on it. Finally, the code prints the length of the my_dict dictionary

Method-5: Using the dictionary comprehension

This method calculates the length of a dictionary using a dictionary comprehension and len() function. The dictionary comprehension converts each key-value pair of the dictionary to a new key-value pair and then calculates the length of the resulting dictionary.

 # Define a dictionary called my_dict with key-value pairs my_dict = # Create a new dictionary using a dictionary comprehension # Get the length of the new dictionary dict_len = len() # Print the length of the original dictionary to the console print("The length of the my_dict dictionary is", dict_len)

The above code creates a dictionary named my_dict with three key-value pairs.

  • It then creates a new dictionary using a dictionary comprehension that has the same key-value pairs as my_dict. It then uses the len() function to get the length of the new dictionary, which is the same as the length of my_dict. Finally, it prints the length of my_dict to the console.
Output: The length of the my_dict dictionary is 3

You may also like to read the following Python tutorials.

Conclusion

In this Python tutorial, we have covered Python dictionary length using the different methods:

  • Using the len() function
  • Using the len() function with keys() method
  • Using the len() function with values() method
  • Using recursion
  • Using the dictionary comprehension

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python Dictionary – Count Items, Keys and Values

Dictionary is a Python collection used to hold data as a key:value pairs, in some programming languages also known as a map. Keys are unique, acting as an index over the values they hold. In this post, we’ll see how to count items, keys, and values inside a Python dictionary.

The most convenient method to count how many pairs the Python dictionary contains is by using the len() method. Result is a number of distinct keys inside a dictionary, therefore this number also represents how many key:value pairs there are.

Built-in items(), keys(), and values() methods

Python dictionary has some handful built-in methods that can help you look up or count different types of values:

  • dict.items() – returns a list that contains tuples representing key:value pairs.
  • dict.keys() – returns all dictionary keys as a list.
  • dict.values() – returns all dictionary values as a list.

Let’s see these methods in action.

>>> vehicles = >>> vehicles.items() dict_items([('vans', 2), ('cars', 12), ('buses', 3)]) >>> vehicles.keys() dict_keys(['vans', 'cars', 'buses']) >>> vehicles.values() dict_values([2, 12, 3])

How to count Python dictionary keys

There are multiple ways how to count keys in a Python dictionary. I will show you three ways:

Use keys() and len() to count dictionary items

Since keys() method already returns all distinct dictionary keys, you can use it in combination with the len() method to count different pairs inside a Python dictionary.

As you can see in the following example, this method returns a correct number of keys in dictionary.

>>> vehicles = >>> len(vehicles.keys()) 3

Use len() to count dictionary items

Although the above example is working, you could write it in shorter way by using only the len() method. The len() method returns the total length of a dictionary, or more precisely, the total number of items in the dictionary.

NOTE - Using len() with keys() to count dictionary keys is slower than using len() only; therefore my recommendation is to use the latter.

Use custom function to count dictionary items

If you are in a need to write a custom function that will count a number of dictionary items, take a look at the following example. We used a simple for loop that iterates over tuples returned by the items() method. Each iteration increases the count value by 1. Here you can also add some additional logic if you need to.

def count_items(dictionary): count = 0 for key, value in dictionary.items(): # Additional logic could go here count += 1 return count vehicles = count_items(vehicles) # 3

Bonus – Python dictionary count duplicate values

As a bonus to this post, let’s see how to count the number of occurrences of each value inside a Python dictionary. To make it easier to understand, let’s introduce the following example. We decided to survey 10 people, with the possibility of answering “yes” or “no”. We store each answer in a dictionary right under that user’s name. The dictionary items look like this:

Now, to count how many times each answer was given, we can help ourselves with Python’s built-in collections module. More precisely, we need a Counter class from the collections module. If we pass a list of values to the Counter, as a result we’ll get key:value pairs that will represent each value and its number of occurrences.

In our example, we get a number of occurrences of each answer in a survey.

>>> from collections import Counter >>> Counter(answers.values()) Counter()

Источник

Оцените статью