已填充排序默认值的列表访问字典

2024-09-30 01:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了以下dictaccs

{
'192.168.20.222': [('access_times', 10), ('bytes', 13147), ('errors', 20)], 
'192.168.60.200': [('access_times', 15), ('bytes', 118922), ('errors', 10)], 
'192.168.60.150': [('access_times', 20), ('bytes', 117989), ('errors', 30)],
'192.168.60.100': [('access_times', 40), ('bytes', 134922), ('errors', 15)],
...
}

如何访问它以检索具有最大访问次数计数的IP的报告?/最大字节数等?你知道吗

下面是生成dict的代码:

accs = defaultdict(list)        
for i in reqs_host.keys():
        if reqs_host[i] > max_requests: 
            accs[i].append(('access_times', reqs_host[i]))
        if bytes_host[i] > max_bytes:
            accs[i].append(('bytes', bytes_host[i]))
        if errors_host[i] > max_errors:
            accs[i].append(('errors', errors_host[i]))
    #
    print dict(accs)

如果一些if没有被执行(即errors_host > max_errors,但是reqs_hosts < max_reqests),我怎么能在相应的dict中仍然有('access_times', X)?所以,要有违约金。你知道吗


Tags: iphostifbytesaccess次数dictmax
2条回答

您可以这样做:

new_list = [(key,value[0][1]) for key,value in a.items()]

new_list.sort(key=lambda x: x[1], reverse=True)

for i in new_list:
    print 'Host',i[0],'accessed:',i[1],'times'

[OUTPUT]
Host 192.168.60.100 accessed: 40 times
Host 192.168.60.150 accessed: 20 times
Host 192.168.60.200 accessed: 15 times
Host 192.168.20.222 accessed: 10 times

>>> print new_list
[('192.168.60.100', 40),
 ('192.168.60.150', 20),
 ('192.168.60.200', 15),
 ('192.168.20.222', 10)]

演示:http://repl.it/Rcp

如果每个条目都有相同的属性,我建议使用命名元组。这样,您可以按名称访问值,但不必将名称与每个值一起存储。 回答您的问题:您必须自己将默认值放入列表中。你知道吗

from collections import namedtuple

HostInfo = namedtuple('HostInfo', 'access_times,bytes,errors')

accs = {}
for i in reqs_host.keys():
    accs[i] = HostInfo(
        reqs_host[i] if reqs_host[i] > max_requests else None,
        bytes_host[i] if bytes_host[i] > max_bytes else None,
        errors_host[i] if errors_host[i] > max_errors else None
    )

for access_times, host in sorted((
            (info.access_times, host)
            for host, info in accs.iteritems()
            if info.access_times is not None
        ), reverse=True):
    print "Host %s accessed %s times"%(host, access_times)

相关问题 更多 >

    热门问题