Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert tuple to a multi nested dictionary in python?

I have a tuple in the following format:

(639283, 298290710, 1385)
(639283, 298290712, 1389)
(639283, 298290715, 1395)
(745310, 470212995, 2061)
(745310, 470213821, 3713)
(745310, 470215360, 6791)
(745310, 470215361, 6793)
(745310, 470215363, 6797)
(911045, 374330803, 4905)
(911045, 374330804, 4907)
(911045, 374330807, 4913)
(911045, 374330808, 4915)
(911045, 374330809, 4917)

I want to convert into a nested dictionary like this:

{639283:{298290710:1385, 298290712:1389, 298290715:1395},745310:{470212995:2061,470213821:3713}............}

Is there a pythonic way of doing this? It seems pretty simple, but i can't seem to figure this out.

like image 823
msakya Avatar asked Feb 17 '14 17:02

msakya


2 Answers

You can use itertools.groupby to group the tuples based on the first item, and then iterate over those groups in a dict-comprehension to get the desired result.

>>> from operator import itemgetter
>>> from pprint import pprint
>>> from itertools import groupby
>>> d = {k: dict(x[1:] for x in g) for k, g in groupby(data, key=itemgetter(0))}
>>> pprint(d)
{639283: {298290710: 1385, 298290712: 1389, 298290715: 1395},
 745310: {470212995: 2061,
          470213821: 3713,
          470215360: 6791,
          470215361: 6793,
          470215363: 6797},
 911045: {374330803: 4905,
          374330804: 4907,
          374330807: 4913,
          374330808: 4915,
          374330809: 4917}}

Where data is your list of tuples or tuple of tuples.

like image 86
Ashwini Chaudhary Avatar answered Oct 18 '22 20:10

Ashwini Chaudhary


You can use tuple unpacking combined with collections.defaultdict to make your life easier.

Create an outer defaultdict with dict as its default value. Then, you can simply loop through your list of tuples once, setting the values appropriately as you go.

from collections import defaultdict

d = defaultdict(dict) # dict where the default values are dicts.
for a, b, c in list_of_tuples: # Each tuple is "key1, key2, value"
    d[a][b] = c

Of course, you presumably know more about what these values actually represent, so you can give your dictionary, and the individual items, better, more descriptive names than a, b, c, and d.

like image 36
Henry Keiter Avatar answered Oct 18 '22 19:10

Henry Keiter