Search code examples
pythonlistdictionarycounter

count frequencies of occurrences of items in a dictionary and update it in dictionary itself


i've a dict d as below:

d
{'EventThread': [40002], 'kworker/u16:13': [80002], 'kworker/u16:0': [80002], 'AudioOut_D': [80002, 80002, 80002, 80002, 80002, 80002], 'putmethod.latin': [80002], 'surfaceflinger': [40002], 'InputDispatcher': [80002]}

I want something similar to:

d
{'AudioOut_D': [80002:6 ,40002:1]}

which indicates frequencies of items

I tried code below:

print((collections.Counter(d['AudioOut_D'])))
Counter({80002: 6})

but then how to update this into dictionay

TIA code for how to generate dict is as follows:

self._sched_task_load_flags = defaultdict(list)
def sched_task_load_handler(self,thread):
        "accepts threads and builds corresponding threads and flags co-relation"
        _sched_task_load_flags = self._sched_task_load_flags
        try:
            while True:
                record = (yield)
                if "sched_task_load"==record["function"]:
                    flags = record["flags"]
                else:
                    print "error in sched_task_load_function_parse"
                    raise Exception

How to combine two operations in loop below:

e = {k: dict(Counter(v)) for k, v in d.iteritems()}

this works great, but I also need to get a list of all flags as below:

for k,v in flags.iteritems():
    list_of_all_flags.append(list(Counter(v)))

how is it possible to combine above two loops in one TIA


Solution

  • Yes you may apply Counter() method on each value as:

    from collections import Counter
    e = {k: dict(Counter(v)) for k, v in d.iteritems()}
    

    Output:

        {'AudioOut_D': {80002: 6},
     'EventThread': {40002: 1},
     'InputDispatcher': {80002: 1},
     'kworker/u16:0': {80002: 1},
     'kworker/u16:13': {80002: 1},
     'putmethod.latin': {80002: 1},
     'surfaceflinger': {40002: 1}}