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 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
.