python 字典嵌套赋值、多个值跟着变化,如何将元组转换为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}............}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值