如何将元组转换为python中的多个嵌套字典? [英] How to convert tuple to a multi nested dictionary in python?

查看:607
本文介绍了如何将元组转换为python中的多个嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的元组:

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

有没有pythonic的方式这样做?

Is there a pythonic way of doing this? It seems pretty simple, but i can't seem to figure this out.

推荐答案

可以使用元组解包与 collections.defaultdict

You can use tuple unpacking combined with collections.defaultdict to make your life easier.

创建一个外部 defaultdict dict 作为其默认值。然后,您可以简单地循环遍历您的元组列表一次,随时随地设置值。

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

当然,您可能更多地了解这些值实际上代表的内容,所以您可以将您的字典和个别项目更好地描述为 a b c d

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.

这篇关于如何将元组转换为python中的多个嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆