我创建了嵌套字典,其中包含从错误日志中提取的值。
ErrorTypes是“Msg”和“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']
]
}
我如何获取计数的代码是什么,所以我知道每个密钥存在多少个错误类型?
这是我到目前为止所做的:
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))
请帮忙!谢谢。
答案 0 :(得分:1)
您可以遍历列表列表并生成set
错误类型,然后只检查该集的长度。根据定义,集合可能只包含唯一的项目,因此您不会重复。
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
制作评论中描述的词典
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})}