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!

3
  • I tried this docs.python.org/2/library/… Commented Feb 22, 2018 at 20:52
  • I asked a similar question a while ago and got some good answers. stackoverflow.com/questions/45019709/… Commented Feb 22, 2018 at 20:56
  • If it's given that the input and output are depth-2, the question and answers are not very general. Commented Dec 10, 2019 at 4:31

3 Answers 3

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}}
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't bad, but instead of D[i].update({_list[0] : _list[1]}) use D[i][_list[0]] = _list[1]. and better yet, use for k, (k2, v) in L: ... D[k][k2] = v`
Yeah sure. Correct. @juanpa.arrivillaga
Use .upate to update the dict with another dynamic dict with many possible entries. You want to update a single key-value pair, don't creat an unecessary intermediate dict to pass to the update method.
Yeah makes sense.
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.

3 Comments

use for k, (k2, v) in L:
my mistake I see now @juanpa.arrivillaga
@juanpa.arrivillaga, let's do it
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}}

1 Comment

@MLam the other answer to this is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.