Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal pythonic way to achieve result output

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

I have input dict like this:

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 want Output like this:

{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 have done code below

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

I had already above answer to achieve my desired output, Is it good approach? Are there any better solutions to achieve result (in pythonic way), must be optimal.

like image 966
Sagar Avatar asked Nov 07 '22 21:11

Sagar


1 Answers

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

There might be some trickery in the dict comprehension that would allow the desired behavior, but it would seem that the code would not become very readable, or understandable, thus rendering it very unpythonic.

In short, your own solution would be quite pythonic.

like image 146
cLupus Avatar answered Nov 15 '22 06:11

cLupus