python - Dynamic nested dictionaries -
just begin know there couple similarly-titled questions on here, none explained quite way nor problem scope same.
i want add nested dictionary entries dynamically.
the use case thus: have python script monitoring network. dictionary created each observed ip protocol (tcp, udp, icmp) observed. sub-dictionary created key destination port (if 1 exists) each of these ip protocols (80, 443, etc.) (note doesn't matter whether sees server port source or destination, servers destination picked http , https examples). each of these destination ports key created corresponding server ip (e.g., ip www.google.com). , dictionary timestamp session first observed key , data/value key being client's ip.
however, want need populated time goes on since won't have data before execution nor @ initialization.
the output akin to:
{  'icmp' :    {  'echo-request' :        {  '<ip_of_www.google.com>' :            {   '<timestamp>' : <some_client_ip> }        }       'echo-reply' :        {  '<ip_of_www.google.com>' :            {   '<timestamp>' : <some_client_ip> }        }    }    'tcp' :    {       '80'         {  '<ip_of_www.google.com>' :            {   '<timestamp>' : <some_client_ip> }            {   '<timestamp>' : <some_client_ip> }        }       '443'         {  '<ip_of_encrypted.google.com>' :            {   '<timestamp>' : <some_client_ip> }            {   '<timestamp>' : <some_client_ip> }            {   '<timestamp>' : <some_client_ip> }            {   '<timestamp>' : <some_client_ip> }        }    } }   thanks!
here are:
def set_nested(dict, value, *path):     level in path[:-1]:         dict = dict.setdefault(level, {})      dict[path[-1]] = value   d = {}  set_nested(d, '127.0.0.1', 'icmp', 'echo', 'google.com', '1 dec 2014') set_nested(d, '127.0.0.1', 'icmp', 'echo', 'google.com', '2 dec 2014') set_nested(d, '127.0.0.1', 'icmp', 'echo', 'yahoo.com', '2 dec 2014') set_nested(d, 'error', 'udp')  pprint import pprint pprint(d)   output:
{'icmp': {'echo': {'google.com': {'1 dec 2014': '127.0.0.1',                                   '2 dec 2014': '127.0.0.1'},                    'yahoo.com': {'2 dec 2014': '127.0.0.1'}}},  'udp': 'error'}   i'd suggest have @ json , tinydb if want store , query results. 
Comments
Post a Comment