我创建了以下词典accs
:
{
'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)],
...
}
如何访问它以检索具有最大access_times数量的IP报告? /最大字节数等?
以下是生成字典的代码:
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)
?所以,有默认设置。
答案 0 :(得分:0)
你可以这样做:
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)]
答案 1 :(得分:0)
如果每个条目总是具有相同的属性,我建议使用命名元组。这样,您可以按名称访问该值,但不必为每个值存储该名称。 要回答您的问题:您必须自己将默认值放入列表中。
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)