Filling in a nested dictionary

I have a long list of nested tuples that I repeat and add in a certain way, so the dictionary is empty:

dict = {}

will be filled as follows:

dict = {a: {b:1,5,9,2,3}, b: {c:7,4,5,6,2,4}, c: {b:3,13,2,4,2}... }

The iteration will check if a nested dictionary exists, and if so, it will add a value, otherwise it will create a nested dictionary. My unsuccessful attempt looks something like this:

longlist = [(1,(a,b)),(2,(b,c)), (3,(c,b)) ... ]
dict = {}
    for each in longlist:
        if dict[each[1][0]][each[1][1]]:
            dict[each[1][0]][each[1][1]].append(each[0])
        else:
            dict[each[1][0]] = {}
            dict[each[1][0]][each[1][1]] = each[0]

Keep in mind that this is a simplified version, so in my real version I am more than the values ​​a, b, c, 1,2,3.

The problem with my approach is that the iteration fails because the dictionary is empty to start with or that the parent element of the socket does not exist in the dict. It gets complicated for me. I was not able to find a lot of information on the Internet about how to solve embedded dictionaries, so I thought it should be good to ask here. I need help.

0
2

, collections.defaultdict

import random
import collections
choices = ['a', 'b', 'c', 'd', 'e', 'f']

longlist = []
for i in range(1, 101):
    longlist.append((i, tuple(random.sample(choices, 2))))

print longlist

final = collections.defaultdict(lambda: collections.defaultdict(list))

for value, (key1, key2) in longlist:
    final[key1][key2].append(value)


print final

, , , , (collection.defaultdict ), .

-

for value (key1, key2) in longlist:
    if not your_dict.get(key1):
        your_dict[key1] = {}
    if not your_dict.get(key1).get(key2):
        your_dict[key1][key2] = []
    your_dict[key1][key2].append(value)

vs " ..." iterable.

for value, keys in longlist:

, , parens.

+3

, , if, , :

if dict_.get(each[1][0], {}).get(each[1][1], None):
    dict_[each[1][0]][each[1][1]].append(each[0])

dict.get , , .

, , , . else ?

dict_[each[1][0]][each[1][1]] = [each[0]]

, dict[...][...].append(...) .

dict . .

for, each[0], each[1] .. - :

for idx, pair in longlist:
    x, y = pair # unpack each pair now
    ...

:

dict_ = {}
for idx, pair in longlist:
    x, y = pair
    if dict_.get(x, {}).get(y, None):
        dict_[x][y].append(idx)

    else:
        dict_[x] = {y : [idx] }

, .

+1

Source: https://habr.com/ru/post/1683573/


All Articles