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

前端 未结 2 1160
离开以前
离开以前 2021-02-08 21:27

I have a tuple in the following format:

(639283, 298290710, 1385)
(639283, 298290712, 1389)
(639283, 298290715, 1395)
(745310, 470212995, 2061)
(745310, 47021382         


        
2条回答
  •  清歌不尽
    2021-02-08 21:54

    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.

提交回复
热议问题