Changing levels of nested dictionary in python

Is there a library that will help me achieve the task of changing the levels of a nested dictionary

For example: From this:

{1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}

For this:

{"A":{1:"i",3:"iii"},"B":{1:"ii",2:"i"},"C":{1:"i",2:"ii"}}

those. the first two levels in the 3-level dictionary are replaced. Thus, instead of 1 map in and 3 maps in, we have a map A in 1 and 3.

The solution should be practical for arbitrary depth and move from one level to another.

+5
source share
3 answers
>>> d = {1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}
>>> keys = ['A','B','C']
>>> e = {key:{k:d[k][key] for k in d if key in d[k]} for key in keys}
>>> e
{'C': {1: 'i', 2: 'ii'}, 'B': {1: 'ii', 2: 'i'}, 'A': {1: 'i', 3: 'iii'}}

Thank god for understanding dictate

+4
source

Basically you read it into an array and take the transpose. An easy way to achieve this would be to use the Pandas data analysis package:

import pandas as pd

df = pd.DataFrame({1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}})
df.transpose().to_dict()

{'A': {1: 'i', 2: nan, 3: 'iii'},
 'B': {1: 'ii', 2: 'i', 3: nan},
 'C': {1: 'i', 2: 'ii', 3: nan}}
+3

, , . , , ~ O (N ^ 2).

, , : - dict_swap_index . [i, j, k]. . , . , [2,0,1] 0 2, 1 0 2 1. - dict_, deep_swap , - deep_swap - swap_two_level_dict .

In essence, the idea is to perform bubble sorting in the dictionary, but instead of replacing items in the list, the levels in the dictionary change.

from collections import defaultdict
def dict_swap_index(dict_, order):
    for pas_no in range(len(order)-1,0,-1):
        for i in range(pas_no):
            if order[i] > order[i+1]:
                temp = order[i]
                order[i] = order[i+1]
                order[i+1] = temp
                dict_ = deep_swap(dict_, i)
    return dict_, order

def deep_swap(dict_, level):
    dict_ = deepcopy(dict_)
    if level==0:
        dict_ = swap_two_level_dict(dict_)
    else:
        for key in dict_:
            dict_[key] = deep_swap(dict_[key], level-1)
    return dict_

def swap_two_level_dict(a):
    b = defaultdict(dict)
    for key1, value1 in a.items():
        for key2, value2 in value1.items():
            b[key2].update({key1: value2})
    return b

eg

test_dict = {'a': {'c': {'e':0, 'f':1}, 'd': {'e':2,'f':3}}, 'b': {'c': {'g':4,'h':5}, 'd': {'j':6,'k':7}}}
result = dict_swap_index(test_dict, [2,0,1])
result
(defaultdict(dict,
             {'c': defaultdict(dict,
                          {'e': {'a': 0},
                           'f': {'a': 1},
                           'g': {'b': 4},
                           'h': {'b': 5}}),
              'd': defaultdict(dict,
                          {'e': {'a': 2},
                           'f': {'a': 3},
                           'j': {'b': 6},
                           'k': {'b': 7}})}),
 [0, 1, 2])
0
source

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


All Articles