I have a tuple in the following format:
(639283, 298290710, 1385)
(639283, 298290712, 1389)
(639283, 298290715, 1395)
(745310, 470212995, 2061)
(745310, 47021382
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.
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
.