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

喜你入骨 提交于 2019-12-03 17:45:48

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21835233/how-to-convert-tuple-to-a-multi-nested-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!