Get Count of Distinct Property Value from an Array of Object in Python

To get the count of distinct property values from an array of objects in Python, you can use the collections.Counter class from the Python standard library. Here's an example.

from collections import Counter

# Sample array of objects
objects = [
    {'id': 1, 'color': 'red'},
    {'id': 2, 'color': 'blue'},
    {'id': 3, 'color': 'red'},
    {'id': 4, 'color': 'green'},
    {'id': 5, 'color': 'blue'},
]

# Extract the property values and count occurrences
property_values = [obj['color'] for obj in objects]
property_counts = Counter(property_values)

# Print the distinct property values and their counts
for value, count in property_counts.items():
    print(f"{value}: {count}")

Output

red: 2
blue: 2
green: 1

In this example, the property_values list is created by extracting the 'color' property value from each object in the array. The Counter class is then used to count the occurrences of each value in property_values. Finally, a loop iterates over the property_counts dictionary to print each distinct property value along with its count.