Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, How to efficiently make a nested dictionary from a list of lists

Tags:

python

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}}
like image 206
Tampa Avatar asked Jun 09 '26 06:06

Tampa


1 Answers

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})}
like image 55
Raymond Hettinger Avatar answered Jun 11 '26 18:06

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!