Skip to content Skip to sidebar Skip to footer

Dynamic Nested Dictionaries

Just to begin I know there are a couple similarly-titled questions on here, but none are explained quite this way nor is the problem scope the same. I want to add nested dictionary

Solution 1:

Here you are:

defset_nested(dict, value, *path):
    for 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')

from 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 also suggest you to have a look at json and tinydb if you want to store and query results.

Post a Comment for "Dynamic Nested Dictionaries"