Python dictionary from two lists - python

I have two lists, one of them is a list of values and the other is a list of dates.
I want to create a dictionary with values and dates as keys. But a lot of the values have the same "key" (date). I need to add the values with the same date (same key) together before making a dictionary.
Both of the lists have the same number of elements but the list of dates has some values duplicated (since every date has more than one value).
What would be the best way to group the values (add them together) based on the keys (dates)?
Examples of the lists
dates = [datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 3, 1, 0, 0),datetime(2014, 3, 1, 0, 0)]
values = [2,7,4,8,4]
I want my dictionary to look like this:
dict = [datetime(2014, 2, 1, 0, 0):13,datetime(2014, 3, 1, 0, 0):8,datetime(2014, 3, 1, 0, 0):4]

If you have repeating dates and want to group the values for repeating keys, use a defaultdict:
from collections import defaultdict
d = defaultdict(int)
for dte, val in zip(dates, values):
d[dte] += val
Output:
defaultdict(<class 'int'>, {datetime.datetime(2014, 2, 1, 0, 0): 13, datetime.datetime(2014, 3, 1, 0, 0): 12})
Or using a normal dict and dict.setdefault:
d = {}
for dte, val in zip(dates,values):
d.setdefault(dte,0)
d[dte] += val
Lastly you can use dict.get with a default value of 0:
d = {}
for dte, val in zip(dates,values):
d[dte] = d.get(dte, 0) + val
The defaultdict is going to be the fastest approach as it is designed exactly for this purpose.

Assuming if this is your input,
>>> dates = ['2015-01-01', '2015-01-01', '2015-01-02', '2015-01-03']
>>> values = [10, 15, 10, 10]
Combine the values,
>>> data = zip(dates, values)
[('2015-01-01', 10), ('2015-01-01', 15), ('2015-01-02', 10), ('2015-01-03', 10)]
Aggregate the values for same dates,
>>> import itertools
>>> new_data = []
>>> for key, group in itertools.groupby(data, lambda x: x[0]):
tmp = [key, 0] #: '0' is the default value
for thing in group:
tmp[1] += thing[1]
new_data.append(tmp)
Print the new_data,
>>> new_data
[['2015-01-01', 25], ['2015-01-02', 10], ['2015-01-03', 10]]
Now build the final dictionary,
>>> dict(new_data)
{'2015-01-03': 10, '2015-01-02': 10, '2015-01-01': 25}

itertools and defaultdict are pretty unnecessary for this. I think that this is simpler and easier to read.
dates = [datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 3, 1, 0, 0),datetime(2014, 3, 1, 0, 0)]
values = [2,7,4,8,4]
combined = {}
for (date,value) in zip(dates,values):
if date in combined:
combined[date] += value
else:
combined[date] = value
Performance analysis
I'm not saying that defaultdict is a bad solution, I was only pointing out that it requires more tacit knowledge to use without pitfalls.
It is not however the fastest solution.
from collections import defaultdict
from datetime import datetime
import timeit
dates = [datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 2, 1, 0, 0),datetime(2014, 3, 1, 0, 0),datetime(2014, 3, 1, 0, 0)]
values = [2,7,4,8,4]
def combine_default_dict(dates=dates,values=values):
d = defaultdict(int)
for dte, val in zip(dates, values):
d[dte] += val
return d
def combine_setdefault(dates=dates,values=values):
d = {}
for dte, val in zip(dates,values):
d.setdefault(dte,0)
d[dte] += val
return d
def combine_get(dates=dates,values=values):
d = {}
for dte, val in zip(dates,values):
d[dte] = d.get(dte, 0) + val
return d
def combine_contains(dates=dates,values=values):
d = {}
for (date,value) in zip(dates,values):
if date in d:
d[date] += value
else:
d[date] = value
return d
def time_them(number=100000):
for func_name in [k for k in sorted(globals().keys()) if k.startswith('combine_')]:
timer = timeit.Timer("{0}()".format(func_name),"from __main__ import {0}".format(func_name))
time_taken = timer.timeit(number=number)
print "{0} - {1}".format(time_taken,func_name)
Yields:
>>> time_them()
0.388070106506 - combine_contains
0.485766887665 - combine_default_dict
0.415601968765 - combine_get
0.472551822662 - combine_setdefault
I've tried it on a couple of different machines and python versions. combine_default_dict competes with combine_setdefault for the slowest. combine_contains has been consistently the fastest.

Related

Counting identical list-elements in a row in Python

I am using Python3. I have a list a of only integers. Now, I want to save the element and the number it repeats itself in a row in another list.
Example:
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
Output:
result = ["6,1", "0, 2", "2, 4", "1, 1", "89, 2"]
# the number before the "," represents the element, the number after the "," represents how many times it repeats itself.
How to efficiently achieve my goal ?
I believe all the solutions given are counting the total occurrences of a number in the list rather than counting the repeating runs of a number.
Here is a solution using groupby from itertools. It gathers the runs and appends them to a dictionary keyed by the number.
from itertools import groupby
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
d = dict()
for k, v in groupby(a):
d.setdefault(k, []).append(len(list(v)))
Dictionary created:
>>> d
{6: [1], 0: [2], 2: [4], 1: [1], 89: [2]}
Note that all runs only had 1 count in their list. If there where other occurrences of a number already seen, there would be multiple counts in the lists (that are the values for dictionary).
for counting an individual element,
us list.count,
i.e, here, for, say 2, we user
a.count(2),
which outputs 4,
also,
set(a) gives the unique elements in a
overall answer,
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
nums = set(a)
result = [f"{val}, {a.count(val)}" for val in set(a)]
print(result)
which gives
['0, 2', '1, 1', '2, 4', '6, 1', '89, 2']
Method 1: using for loop
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
result = []
a_set = set(a) # transform the list into a set to have unique integer
for nbr in a_set:
nbr_count = a.count(nbr)
result.append("{},{}".format(nbr, nbr_count))
print(result) # ['0,2', '1,1', '2,4', '6,1', '89,2']
Method 2: using list-comprehensions
result = ["{},{}".format(item, a.count(item)) for item in set(a)]
print(result) # ['0,2', '1,1', '2,4', '6,1', '89,2']
you can use Python List count() Method, method returns the number of elements with the specified value.
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
print ({x:a.count(x) for x in a})
output:
{6: 1, 0: 2, 2: 4, 1: 1, 89: 2}
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
dic = dict()
for i in a:
if(i in dic):
dic[i] = dic[i] + 1
else:
dic[i] = 1
result = []
for i in dic:
result.append(str(i) +"," + str(dic[i]))
Or:
from collections import Counter
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
mylist = [Counter(a)]
print(mylist)
You can use Counter from collections:
from collections import Counter
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
counter = Counter(a)
result = ['{},{}'.format(k, v) for k,v in counter.items()]

Dictionary of lists to nested dictionary

I have the following dictionary {44: [0, 1, 0, 3, 6]} and need to convert this to dict1 = {44: {0:0, 1:1, 2:0, 3:3, 4:6}} but my current for loop doesn't work:
maxnumbers = 5 #this is how many values are within the list
for i in list(range(maxnumbers)):
for k in list(dict1.keys()):
for g in dict1[k]:
newdict[i] = g
print(num4)
Can you help me? Thanks in advance.
You can use a dictionary comprehension with enumerate:
d = {44: [0, 1, 0, 3, 6]}
{k:dict(enumerate(v)) for k,v in d.items()}
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
Use a simple nested dictionary-comprehension that uses enumerate:
d = {44: [0, 1, 0, 3, 6]}
print({k: {i: x for i, x in enumerate(v)} for k, v in d.items()})
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
a = {44: [0, 1, 0, 3, 6]}
a= {i:{j:a[i][j] for i in a for j in range(len(a[i]))}}
print(a)
output
{44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
Why your current implementation doesn't work:
for i in list(range(maxnumbers)):
for k in list(dict1.keys()):
for g in dict1[k]:
# this will iterate over all of the values in
# d1[k] and the i: v pair will be overwritten by
# the last value
newdict[i] = g
Taken in steps, this would look like:
# for value in [0, 1, 0, 3, 6]: Just take this set of values as an example
# first, value is 0, and say we are on i = 1, in the outer for loop
newdict[1] = 0
# Then it will progress to value = 1, but i has not changed
# which overwrites the previous value
newdict[1] = 1
# continues until that set of values is complete
In order to fix this, you'll want i and the values of dict1[k] to increment together. This can be accomplished with zip:
for index, value in zip(range(maxnumbers), dict1[k]):
newdict[index] = value
Also, if you need access to both the keys and values, use dict.items():
for k, values in dict1.items():
# then you can use zip on the values
for idx, value in zip(range(maxnumbers), values):
However, the enumerate function already facilitates this:
for k, values in dict1.items():
for idx, value in enumerate(values):
# rest of loop
This is more robust, since you don't have to find what maxnumbers is ahead of time.
To do this in the traditional for loop that you've been using:
new_dict = {}
for k, v in dict1.items():
sub_d = {} # create a new sub_dictionary
for i, x in enumerate(v):
sub_d[i] = x
# assign that new sub_d as an element in new_dict
# when the inner for loop completes
new_dict[k] = sub_d
Or, more compactly:
d = {44: [0, 1, 0, 3, 6]}
new_d = {}
for k, v in d.items():
new_d[k] = dict(enumerate(v))
Where the dict constructor will take an iterable of 2-element tuples as an argument, which enumerate provides

Get Duplicate values when creating a dictionary with list comprehension in Python

I have two lists as follows:
list1 = [0, 0, 1]
list2 = [0, 1, 2]
I zip them using:
zipped_list = zip(list1,list2)
The result is zipped_list = [(0, 0), (0, 1), (1, 2)]
Now, I want to create a dictionary using list comprehension as follows:
d = {k:v for k, v in zipped_list}
The result is d={0: 1, 1: 2}
That is for the key = 0 in zipped_list, the dictionary contains only the last occurrence of key, value pair.
The question is: how can I get all occurrences of key, value pairs for duplicate keys and not only the last one?
In the particular example, I would like to get
d={0: 0, 0: 1, 1: 2}
That is not possible because you cannot have dicts with duplicate keys.
You can instead try to have a list of all values under the same key.
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> zipped_list = [(0, 0), (0, 1), (1, 2)]
>>> for k,v in zipped_list:
... d[k].append(v)
...
>>> d
defaultdict(<type 'list'>, {0: [0, 1], 1: [2]})
Basically the same approach #Ashish is using but without any external modules (imports)
list1 = [0, 0, 1]
list2 = [0, 1, 2]
zipped = zip(list1, list2)
d = {}
for items in zipped:
res = d.setdefault(items[0], [])
res.append(items[1])
print(d) # prints: {0: [0, 1], 1: [2]}
And yes, this can be achieved with any other hashable data structure if it is the keys you mean. list1 could have been list1 = ['a', 'a', 'b'] for example.
If you find setdefault too fancy take a look at its documentation.

Python: calculate value for each pair of values in list

I have a dictionary consisting of key:[list] in which the list is a fixed and even number of binary values, ie:
{'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
For each key, I need to return a new value for each pair of values in the original dict, such that for pair(1,1) = 3, pair(0,1) = 2, pair(1,0) = 1, pair(0,0) = 0.
For the example above, output would be:
{'a':[2,1,2],'b':[3,1,0]}
New to both python and programming in general, and haven't found what I'm looking for on SO. Suggestions appreciated.
First attack just the pairing part:
def paired(binlist, map={(1, 1): 3, (0, 1): 2, (1, 0): 1, (0, 0): 0}):
return [map[tuple(binlist[i:i + 2])] for i in range(0, len(binlist), 2)]
Then apply this to your dictionary:
{k: paired(v) for k, v in input_dictionary.iteritems()}
Demo:
>>> paired([0,1,1,0,0,1])
[2, 1, 2]
>>> paired([1,1,1,0,0,0])
[3, 1, 0]
>>> input_dictionary = {'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
>>> {k: paired(v) for k, v in input_dictionary.iteritems()}
{'a': [2, 1, 2], 'b': [3, 1, 0]}
>>> D = {'a': [0, 1, 1, 0, 0, 1],'b': [1, 1, 1, 0, 0, 0]}
>>> {k: [v[i] + 2 * v[i+1] for i in range(0, len(v), 2)] for k, v in D.items()}
{'a': [2, 1, 2], 'b': [3, 1, 0]}
A small snippet I could come up with was :
>>> testDict = {'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
>>> referenceDict = {(0, 1):2, (0, 0):0, (1, 0):1, (1, 1):3}
>>> for key, value in testDict.items():
finalList = [referenceDict[elem] for elem in zip(value[::2], value[1::2])]
testDict[key] = finalList
>>> testDict
{'a': [2, 1, 2], 'b': [3, 1, 0]}
value[::2] is Python's Slice Notation.
Packing this up into a function for use :
def testFunction(inputDict):
referenceDict = {(0, 1):2, (0, 0):0, (1, 0):1, (1, 1):3}
for key, value in inputDict.items():
finalList = [referenceDict[elem] for elem in zip(value[::2], value[1::2])]
inputDict[key] = finalList
return inputDict
Example -
>>> testFunction({'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]})
{'a': [2, 1, 2], 'b': [3, 1, 0]}

How to count the frequency of the elements in an unordered list? [duplicate]

This question already has answers here:
Using a dictionary to count the items in a list
(8 answers)
Closed 7 months ago.
Given an unordered list of values like
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
How can I get the frequency of each value that appears in the list, like so?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
In Python 2.7 (or newer), you can use collections.Counter:
>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]
If you are using Python 2.6 or older, you can download an implementation here.
If the list is sorted, you can use groupby from the itertools standard library (if it isn't, you can just sort it first, although this takes O(n lg n) time):
from itertools import groupby
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]
Output:
[4, 4, 2, 1, 2]
Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]
Count the number of appearances manually by iterating through the list and counting them up, using a collections.defaultdict to track what has been seen so far:
from collections import defaultdict
appearances = defaultdict(int)
for curr in a:
appearances[curr] += 1
In Python 2.7+, you could use collections.Counter to count items
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]
Counting the frequency of elements is probably best done with a dictionary:
b = {}
for item in a:
b[item] = b.get(item, 0) + 1
To remove the duplicates, use a set:
a = list(set(a))
You can do this:
import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)
Output:
(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
The first array is values, and the second array is the number of elements with these values.
So If you want to get just array with the numbers you should use this:
np.unique(a, return_counts=True)[1]
Here's another succint alternative using itertools.groupby which also works for unordered input:
from itertools import groupby
items = [5, 1, 1, 2, 2, 1, 1, 2, 2, 3, 4, 3, 5]
results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}
results
format: {value: num_of_occurencies}
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
I would simply use scipy.stats.itemfreq in the following manner:
from scipy.stats import itemfreq
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq = itemfreq(a)
a = freq[:,0]
b = freq[:,1]
you may check the documentation here: http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]
counter=Counter(a)
kk=[list(counter.keys()),list(counter.values())]
pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
Suppose we have a list:
fruits = ['banana', 'banana', 'apple', 'banana']
We can find out how many of each fruit we have in the list like so:
import numpy as np
(unique, counts) = np.unique(fruits, return_counts=True)
{x:y for x,y in zip(unique, counts)}
Result:
{'banana': 3, 'apple': 1}
This answer is more explicit
a = [1,1,1,1,2,2,2,2,3,3,3,4,4]
d = {}
for item in a:
if item in d:
d[item] = d.get(item)+1
else:
d[item] = 1
for k,v in d.items():
print(str(k)+':'+str(v))
# output
#1:4
#2:4
#3:3
#4:2
#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}
For your first question, iterate the list and use a dictionary to keep track of an elements existsence.
For your second question, just use the set operator.
def frequencyDistribution(data):
return {i: data.count(i) for i in data}
print frequencyDistribution([1,2,3,4])
...
{1: 1, 2: 1, 3: 1, 4: 1} # originalNumber: count
I am quite late, but this will also work, and will help others:
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))
for x in a_l:
freq_list.append(a.count(x))
print 'Freq',freq_list
print 'number',a_l
will produce this..
Freq [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counts = dict.fromkeys(a, 0)
for el in a: counts[el] += 1
print(counts)
# {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
# 1. Get counts and store in another list
output = []
for i in set(a):
output.append(a.count(i))
print(output)
# 2. Remove duplicates using set constructor
a = list(set(a))
print(a)
Set collection does not allow duplicates, passing a list to the set() constructor will give an iterable of totally unique objects. count() function returns an integer count when an object that is in a list is passed. With that the unique objects are counted and each count value is stored by appending to an empty list output
list() constructor is used to convert the set(a) into list and referred by the same variable a
Output
D:\MLrec\venv\Scripts\python.exe D:/MLrec/listgroup.py
[4, 4, 2, 1, 2]
[1, 2, 3, 4, 5]
Simple solution using a dictionary.
def frequency(l):
d = {}
for i in l:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
for k, v in d.iteritems():
if v ==max (d.values()):
return k,d.keys()
print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
#!usr/bin/python
def frq(words):
freq = {}
for w in words:
if w in freq:
freq[w] = freq.get(w)+1
else:
freq[w] =1
return freq
fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()
from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
dictionary = OrderedDict()
for val in lists:
dictionary.setdefault(val,[]).append(1)
return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]
To remove duplicates and Maintain order:
list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]
i'm using Counter to generate a freq. dict from text file words in 1 line of code
def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
[wrd.lower() for wrdList in
[words for words in
[re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
for wrd in wrdList])
For the record, a functional answer:
>>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> import functools
>>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
[4, 4, 2, 1, 2]
It's cleaner if you count zeroes too:
>>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e<len(acc) else acc+[0 for _ in range(e-len(acc))]+[1], L, [])
[0, 4, 4, 2, 1, 2]
An explanation:
we start with an empty acc list;
if the next element e of L is lower than the size of acc, we just update this element: v+(i==e) means v+1 if the index i of acc is the current element e, otherwise the previous value v;
if the next element e of L is greater or equals to the size of acc, we have to expand acc to host the new 1.
The elements do not have to be sorted (itertools.groupby). You'll get weird results if you have negative numbers.
Another approach of doing this, albeit by using a heavier but powerful library - NLTK.
import nltk
fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
Found another way of doing this, using sets.
#ar is the list of elements
#convert ar to set to get unique elements
sock_set = set(ar)
#create dictionary of frequency of socks
sock_dict = {}
for sock in sock_set:
sock_dict[sock] = ar.count(sock)
For an unordered list you should use:
[a.count(el) for el in set(a)]
The output is
[4, 4, 2, 1, 2]
Yet another solution with another algorithm without using collections:
def countFreq(A):
n=len(A)
count=[0]*n # Create a new list initialized with '0'
for i in range(n):
count[A[i]]+= 1 # increase occurrence for value A[i]
return [x for x in count if x] # return non-zero count
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)
You can use the in-built function provided in python
l.count(l[i])
d=[]
for i in range(len(l)):
if l[i] not in d:
d.append(l[i])
print(l.count(l[i])
The above code automatically removes duplicates in a list and also prints the frequency of each element in original list and the list without duplicates.
Two birds for one shot ! X D
This approach can be tried if you don't want to use any library and keep it simple and short!
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)
o/p
[4, 4, 2, 1, 2]

Categories

Resources