List of groups / dictionary counts based on value

I have a list of tokens that looks something like this:

[{
    Value: "Blah",
    StartOffset: 0,
    EndOffset: 4
}, ... ]

What I want to do is count how many times each value happens in the token list.

In VB.Net, I would do something like ...

Tokens = Tokens.
GroupBy(Function(x) x.Value).
Select(Function(g) New With {
           .Value = g.Key,
           .Count = g.Count})

What is the equivalent in Python?

+5
source share
4 answers

IIUC, you can use collections.Counter:

>>> from collections import Counter
>>> tokens = [{"Value": "Blah", "SO": 0}, {"Value": "zoom", "SO": 5}, {"Value": "Blah", "SO": 2}, {"Value": "Blah", "SO": 3}]
>>> Counter(tok['Value'] for tok in tokens)
Counter({'Blah': 3, 'zoom': 1})

if you only need an account. If you want them to be grouped by value, you can use itertools.groupbysomething like:

>>> from itertools import groupby
>>> def keyfn(x):
        return x['Value']
... 
>>> [(k, list(g)) for k,g in groupby(sorted(tokens, key=keyfn), keyfn)]
[('Blah', [{'SO': 0, 'Value': 'Blah'}, {'SO': 2, 'Value': 'Blah'}, {'SO': 3, 'Value': 'Blah'}]), ('zoom', [{'SO': 5, 'Value': 'zoom'}])]

although this is a bit more complicated because it groupbyrequires grouped terms to be contiguous, so you first need to sort the key first.

+14
source

, python, dictionnaries:

my_list = [{'Value': 'Blah',
            'StartOffset': 0,
            'EndOffset': 4},
           {'Value': 'oqwij',
            'StartOffset': 13,
            'EndOffset': 98},
           {'Value': 'Blah',
            'StartOffset': 6,
            'EndOffset': 18}]

:

len([i for i in a if i['Value'] == 'Blah']) # returns 2
+2
import collections

# example token list
tokens = [{'Value':'Blah', 'Start':0}, {'Value':'BlahBlah'}]

count=collections.Counter([d['Value'] for d in tokens])
print count

Counter({'BlahBlah': 1, 'Blah': 1})
+1
token = [{
    'Value': "Blah",
    'StartOffset': 0,
    'EndOffset': 4
}, ... ]

value_counter = {}

for t in token:
    v = t['Value']
    if v not in value_counter:
        value_counter[v] = 0
    value_counter[v] += 1

print value_counter
0

All Articles