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

前端 未结 2 1118
离开以前
离开以前 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 22:03

    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.

提交回复
热议问题