counting the frequency of elements in a list using a dictionary:-
Python में Dictionary का उपयोग करके भी सभी elements की frequency को आसानी से count और store किया जा सकता है।
इस method में:
Element → Key
Frequency → Value
के रूप में store होती है।
Example :-
numbers = [10, 20, 10, 30, 10, 20]
frequency = {}
for num in numbers:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
print(frequency)
Output:
{10: 3, 20: 2, 30: 1}
Explanation :-
सबसे पहले एक empty dictionary बनाई जाती है:
frequency = {}
जब 10 पहली बार मिलता है:
frequency[10] = 1
जब 10 दोबारा मिलता है:
frequency[10] += 1
इस प्रकार 10 की frequency 3 हो जाती है।
अंत में Dictionary इस प्रकार होती है:
10 → 3
20 → 2
30 → 1
इसलिए:
{10: 3, 20: 2, 30: 1}
IN ENGLISH -
Counting the Frequency of Elements in a List Using a Dictionary :-
In Python, a Dictionary can also be used to easily count and store the frequency of all elements in a List.
In this method:
Element → Key
Frequency → Value
Example :-
numbers = [10, 20, 10, 30, 10, 20]
frequency = {}
for num in numbers:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
print(frequency)
Output :-
{10: 3, 20: 2, 30: 1}
Explanation :-
First, an empty Dictionary is created:
frequency = {}
When 10 is found for the first time:
frequency[10] = 1
When 10 is found again:
frequency[10] += 1
In this way, the frequency of 10 becomes 3.
Finally, the Dictionary looks like this:
10 → 3
20 → 2
30 → 1
Therefore:
{10: 3, 20: 2, 30: 1}