The optimal pythonic way to achieve results

I need help regarding an optimal and good solution for my answer.

I have an input dict as follows:

a = { (1, 1403): {1:0.1, 2:0.1, 3:0.2}, (1, 1412): {1:0.1, 2:0.1, 3:0.2}, (1, 1411): {1:0.1, 2:0.1, 3:0.2}, (1, 1402): {1:0.1, 2:0.1, 3:0.2}, (1, 1411): {1:0.1, 2:0.1, 3:0.2}, (2, 1501): {1:0.1, 2:0.1, 3:0.2}, (2, 1511): {1:0.1, 2:0.1, 3:0.2}, (2, 1700): {1:0.1, 2:0.1, 3:0.2}, (2, 1120): {1:0.1, 2:0.1, 3:0.2}, (2, 2133): {1:0.1, 2:0.1, 3:0.2}, (2, 2130): {1:0.1, 2:0.1, 3:0.2}, (2, 901): {1:0.1, 2:0.1, 3:0.2}, (3, 1111): {1:0.1, 2:0.1, 3:0.2}, } 

I need the output as follows:

 {1: { 1403: {1: 0.1, 2: 0.1, 3: 0.2}, 1402: {1: 0.1, 2: 0.1, 3: 0.2}, 1411: {1: 0.1, 2: 0.1, 3: 0.2}, 1412: {1: 0.1, 2: 0.1, 3: 0.2}}, 2: {1120: {1: 0.1, 2: 0.1, 3: 0.2}, 2130: {1: 0.1, 2: 0.1, 3: 0.2}, 1700: {1: 0.1, 2: 0.1, 3: 0.2}, 901: {1: 0.1, 2: 0.1, 3: 0.2}, 1511: {1: 0.1, 2: 0.1, 3: 0.2}, 1501: {1: 0.1, 2: 0.1, 3: 0.2}, 2133: {1: 0.1, 2: 0.1, 3: 0.2}}, 3: {1111: {1: 0.1, 2: 0.1, 3: 0.2}}} 

I made the code below

 data_dict = defaultdict(dict) for (a,b), c in a.items(): data_dict[a].update({b:c}) 

I already had an answer to achieve the desired result, is this a good approach? Are there any better solutions to achieve the result (in Piton's style), should be optimal.

+5
source share
1 answer

One way would be to use a dict understanding, as described in PEP 274 , which may be more Pythonic. However, the naive solution result = {a: {b: c} for (a, b), c in a.items()} does not work as desired. (He will give you a dictionary with three keys, each of which contains one dictionary).

In the understanding of dict, there may be some kind of trickery that would allow the desired behavior, but it would seem that the code would not become very readable or understandable, thereby making it very troubled.

In short, your own solution would be pretty pythonic.

0
source

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


All Articles