Python Program to calculate Dictionaries frequencies

Python Program to calculate Dictionaries frequencies

Calculating frequencies of items (keys) in a dictionary means counting how often each unique item appears. If you have a list of dictionaries and you want to calculate the frequency of specific keys or values across those dictionaries, you can do so with the help of a defaultdict.

In this tutorial, I'll demonstrate how to calculate the frequency of keys and values from a list of dictionaries:

1. Frequency of Keys Across Dictionaries:

Here's a program to calculate the frequency of keys across a list of dictionaries:

from collections import defaultdict def key_frequencies(dict_list): frequencies = defaultdict(int) for d in dict_list: for key in d: frequencies[key] += 1 return frequencies dict_list = [ {'a': 5, 'b': 6}, {'a': 7, 'c': 8}, {'b': 9, 'c': 10, 'd': 11} ] print(key_frequencies(dict_list)) 

2. Frequency of Values Across Dictionaries for a Specific Key:

If you want to calculate the frequency of values for a specific key across dictionaries, you can use the following program:

from collections import defaultdict def value_frequencies_for_key(dict_list, target_key): frequencies = defaultdict(int) for d in dict_list: if target_key in d: frequencies[d[target_key]] += 1 return frequencies dict_list = [ {'a': 5, 'b': 6}, {'a': 5, 'c': 8}, {'a': 6, 'b': 9, 'c': 10, 'd': 11} ] print(value_frequencies_for_key(dict_list, 'a')) 

Explanation:

  • We use defaultdict from the collections module, which allows us to create a dictionary where if a key doesn't already exist, it's created with a default value.
  • The key_frequencies function calculates the frequency of keys across the list of dictionaries.
  • The value_frequencies_for_key function calculates the frequency of values for a specific key across the dictionaries.

In the provided examples:

  1. For key_frequencies, the output will show how many times each key appeared across all dictionaries.
  2. For value_frequencies_for_key, the output will show how many times each value appeared for the specific key across all dictionaries.

More Tags

barcode xlwt plesk google-search git-config publish asp.net-web-api-routing resources iot spring-boot-starter

More Programming Guides

Other Guides

More Programming Examples