简体   繁体   中英

Count # of unique values for dictionary key in Python

I have created nested dictionary with values extracted from error logs.

ErrorTypes are "Msg" and "Cmd"

dict1 = {
    '1234': [
        ['2014-09-19 09:55:41', 1234, 'Msg', 'N/A', 'N/A'],
        ['2014-09-19 10:22:22', 123, 'Msg', 123, 'N/A'],
        ['2014-09-19 12:22:21', 1234, 'Cmd', 123, 'N/A']
    ]
}

What is the code for how I can get a count so I know how many of each error type exists for each key?

This is what I have so far:

from collections import Counter

dict2 = {}
for k in dict1:
        for v in k:
                dict2[str(k)].append(str(k),collection.Counter(v[k] for v in dict1))

Please help! Thank you.

You could walk through the list of lists and make a set of error types, then just check the length of that set. Sets, by definition, may only contain unique items so you will not have repeats.

dict1 = {'1234': [['2014-09-19 09:55:41', 1234, 'Msg', 'N/A', 'N/A'],
                  ['2014-09-19 10:22:22', 123, 'Msg', 123, 'N/A'],
                  ['2014-09-19 12:22:21', 1234, 'Cmd', 123, 'N/A']]}

>>> set(i[2] for i in dict1['1234'])
set(['Msg', 'Cmd'])

>>> len(set(i[2] for i in dict1['1234']))
2

To make the dictionary you described in your comment

dict1 = {'1234': [['2014-09-19 09:55:41', 1234, 'Msg', 'N/A', 'N/A'],
                  ['2014-09-19 10:22:22', 123, 'Msg', 123, 'N/A'],
                  ['2014-09-19 12:22:21', 1234, 'Cmd', 123, 'N/A']],
         '5678': [['2014-09-19 09:55:41', 1234, 'Foo', 'N/A', 'N/A'],
                  ['2014-09-19 10:22:22', 123, 'Bar', 123, 'N/A'],
                  ['2014-09-19 12:22:21', 1234, 'Bar', 123, 'N/A']]}

from collections import Counter

>>> {key : Counter([i[2] for i in dict1[key]]) for key in dict1.keys()}
{'1234': Counter({'Msg': 2, 'Cmd': 1}),
 '5678': Counter({'Bar': 2, 'Foo': 1})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM