2

I have a list as below:

L = [[0,[1,1.0]],
     [0,[2,0.5]],
     [1,[3,3.0]],
     [2,[1,0.33],
     [2,[4,1.5]]]

I would like to convert it into a nested dict as below:

D = {0:{1: 1.0,
        2: 0.5},
     1:{3: 3.0},
     2:{1: 0.33,
        4: 1.5}
     }

I'm not sure how to convert it. Any suggestion? Thank you!

smci
  • 32,567
  • 20
  • 113
  • 146
MLam
  • 161
  • 1
  • 2
  • 10
  • I tried this https://docs.python.org/2/library/collections.html#collections.defaultdict – MLam Feb 22 '18 at 20:52
  • I asked a similar question a while ago and got some good answers. https://stackoverflow.com/questions/45019709/how-to-process-dicts-within-nested-lists-in-an-ordered-manner-with-python – Calvin Ellington Feb 22 '18 at 20:56
  • If it's given that the input and output are depth-2, the question and answers are not very general. – smci Dec 10 '19 at 04:31

3 Answers3

7

Beginners friendly,

D = {}
for i, _list in L:
    if i not in D:
        D[i] = {_list[0] : _list[1]}
    else:
        D[i][_list[0]] = _list[1]})

Result:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
Reck
  • 1,388
  • 11
  • 20
6

With collections.defaultdict([default_factory[, ...]]) class:

import collections

L = [[0,[1,1.0]],
     [0,[2,0.5]],
     [1,[3,3.0]],
     [2,[1,0.33]],
     [2,[4,1.5]]]

d = collections.defaultdict(dict)
for k, (sub_k, v) in L:
    d[k][sub_k] = v

print(dict(d))

The output:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}

  • collections.defaultdict(dict) - the first argument provides the initial value for the default_factory attribute; it defaults to None. Setting the default_factory to dict makes the defaultdict useful for building a dictionary of dictionaries.
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

You can use itertools.groupby:

import itertools
L = [[0,[1,1.0]],
 [0,[2,0.5]],
 [1,[3,3.0]],
 [2,[1,0.33]],
 [2,[4,1.5]]
 ]

new_l = {a:dict([i[-1] for i in b]) for a, b in itertools.groupby(L, key=lambda x:x[0])}

Output:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102