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.
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})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With