user3547740
user3547740

Reputation:

Finding occurence in list of lists

I have a list of lists containing different details which has been populated like this:

 [['sku','3','batchid',4], ['sku','9','batchid',5], ['sku','3','batchid',5], ['sku','3','batchid',5]]

I need to find the occurrence of 4 element in list of lists and to display those which appear more than once in the list of lists. Any guidance would be appreciated.

Expected output:

{"3":[['sku','9','batchid',5],['sku','3','batchid',5],['sku','3','batchid',5]],
"1":[['sku','3','batchid',5]['sku','3','batchid',5]]}

Upvotes: 0

Views: 106

Answers (1)

vaultah
vaultah

Reputation: 46513

Count 4th elements

from collections import Counter
from operator import itemgetter
print(Counter(map(itemgetter(3), lst)))
# Counter({5: 3, 4: 1}) and it will act as a normal dictionary

or get the most common list

from operator import itemgetter
print(max(lst, key=lst.count)) # ['sku', '3', 'batchid', 5]

UPDATE:

If your expected output is

{"3":[['sku','9','batchid',5],['sku','3','batchid',5],['sku','3','batchi‌​d',5]], "1":[['sku','3','batchid',4]]}

then here's the solution

from itertools import groupby
lst.sort(key=lambda x: x[3])
d = {}
for x, y in groupby(lst, key=lambda x: x[3]):
    y = list(y)
    d[len(y)] = y

print(d)

that outputs

{1: [['sku', '3', 'batchid', 4]],
 3: [['sku', '9', 'batchid', 5],
     ['sku', '3', 'batchid', 5],
     ['sku', '3', 'batchid', 5]]}

In case of multiple elements with the same number of occurrences:

from itertools import groupby
from collections import defaultdict
lst.sort(key=lambda x: x[3])
d = defaultdict(list)
for x, y in groupby(lst, key=lambda x: x[3]):
    y = list(y)
    d[len(y)].extend(y)

print(d)

Upvotes: 3

Related Questions