[英]Python, How to efficiently make a nested dictionary from a list of lists
I have a list of lists that looks like this 我有一个列表,看起来像这样
[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]
I need to make a dictionary that has counts of the status codes by ip address. 我需要通过ip地址创建一个包含状态代码计数的字典。
results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}
The tools in collections make short work of this problem: 集合中的工具可以解决这个问题:
>>> from collections import defaultdict, Counter
>>> d = defaultdict(Counter)
>>> for ip, code in [['ip1',404], ['ip1',200], ['ip1',200],
['ip2',200], ['ip2',200], ['ip2',504]]:
d[ip][code] += 1
>>> dict(d)
{'ip2': Counter({200: 2, 504: 1}), 'ip1': Counter({200: 2, 404: 1})}
>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(int))
>>> ips = [['ip1',404],['ip1',200],['ip1',200],['ip2',200],['ip2',200],['ip2',504]]
>>> for ip,num in ips:
d[ip][num] += 1
>>> d
defaultdict(<function <lambda> at 0x00000000035D6648>, {'ip2': defaultdict(<class 'int'>, {200: 2, 504: 1}), 'ip1': defaultdict(<class 'int'>, {200: 2, 404: 1})})
try this: 尝试这个:
values = [['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]
counts = {}
for value in values:
ip, status_code = value
if ip not in counts:
counts[ip] = {}
if status_code not in counts[ip]:
counts[ip][status_code] = 0
counts[ip][status_code] += 1
{'ip2': {200: 2, 504: 1}, 'ip1': {200: 2, 404: 1}}
it should work on virtually any python version. 它应该适用于几乎任何python版本。
>>> l
[['ip1', 404],
['ip1', 200],
['ip1', 200],
['ip2', 200],
['ip2', 200],
['ip2', 504]]
>>> {ip: {code: l.count([ip, code])
... for code in (p[1] for p in l if p[0]==ip)}
... for ip in (p[0] for p in l)}
{'ip1': {200: 2, 404: 1}, 'ip2': {200: 2, 504: 1}}
L = [[ip1,404], [ip1,200], [ip1,200], [ip2,200], [ip2,200], [ip2,504]]
D = {}
for entry in L:
ip = entry[0]
code = entry[1]
ip_entry = D.get(ip, {})
ip_entry[code] = ip_entry.get(code, 0) + 1
D[ip] = ip_entry
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.