Python,如何从列表列表中有效地创建嵌套字典

时间:2012-06-17 07:25:05

标签: python

我有一个类似于此列表的列表

[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]

我需要制作一个按IP地址计算状态代码的字典。

results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}

5 个答案:

答案 0 :(得分:9)

集合中的工具可以解决这个问题:

>>> 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})}

答案 1 :(得分:3)

>>> 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})})

答案 2 :(得分:2)

试试这个:

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}}

它几乎适用于任何python版本。

答案 3 :(得分:0)

>>> 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}}

答案 4 :(得分:0)

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