Is it possible to count the duplicates from a list?
Let’s say I have this list:
my_list = [1, 2, 3, 6, 2, 1, 6]
And i want an output like this:
my_list_duplicates = {1: 2, 2: 2, 3: 1, 6: 2}
Is that possible?
Is it possible to count the duplicates from a list?
Let’s say I have this list:
my_list = [1, 2, 3, 6, 2, 1, 6]
And i want an output like this:
my_list_duplicates = {1: 2, 2: 2, 3: 1, 6: 2}
Is that possible?
The absolute easiest way is to use the collections.Counter
object from the standard library:
>>> import collections
>>> my_list = [1, 2, 3, 6, 2, 1, 6]
>>> dict(collections.Counter(my_list))
{1: 2, 2: 2, 3: 1, 6: 2}
If you do not want to use an inbuilt function, you could use a hash map to store the count of the values as your iterate through the list
my_list = [1, 2, 3, 6, 2, 1, 6]
my_list_duplicates = {}
for i in my_list:
if my_list_duplicates.get(i):
my_list_duplicates[i] += 1
else:
my_list_duplicates[i] = 1
print(my_list_duplicates)
Output
{1: 2, 2: 2, 3: 1, 6: 2}
1.You can use Counter from collections package .
from collections import Counter
my_list = [1, 2, 3, 6, 2, 1, 6]
list_1 = Counter(my_list)
print(list_1)
2.second option is you can iterate it in a loop for each value to find its duplicate and store them in a dictionary .
my_list = [1, 2, 3, 6, 2, 1, 6]
duplicate_dict = {i: my_list.count(i) for i in my_list
print(duplicate_dict)
You can do that with count
:
my_list_duplicates = {i: my_list.count(i) for i in my_list}