numpy 在python中从数组生成dict

a7qyws3x  于 2023-01-26  发布在  Python
关注(0)|答案(1)|浏览(154)

我想从一个给定的数组中创建一个字典。
我有这个。

{1: (0, 4, 12, 27, 25, 58),
 2: (4, 0, 24, 16, 29, 38),
 3: (12, 24, 0, 31, 14, 30),
 4: (27, 16, 31, 0, 21, 8),
 5: (25, 29, 14, 21, 0, 11),
 6: (58, 38, 30, 8, 11, 0)}

我想得到这个

{1: {1: 0, 2: 4, 3: 12, 4: 27, 5: 25, 6: 58},
 2: {1: 4, 2: 0, 3: 24, 4: 16, 5: 29, 6: 38},
 3: {1: 12, 2: 24, 3: 0, 4: 31, 5: 14, 6: 30},
 4: {1: 27, 2: 16, 3: 31, 4: 0, 5: 21, 6: 8},
 5: {1: 25, 2: 29, 3: 14, 4: 21, 5: 0, 6: 11},
 6: {1: 58, 2: 38, 3: 30, 4: 8, 5: 11, 6: 0}}

我怎样才能得到这个?

mrphzbgm

mrphzbgm1#

我没有看到任何数组,看起来你有一个包含元组值的字典。
您可以将字典解析与enumerate()沿着使用,以获得所需的结果。

new_dict = {key: dict(enumerate(value, 1)) for key, value in old_dict.items()}

相关问题