Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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
.
–
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.