把集合词典变成列表词典

2021-05-16 07:08:02 发布

您现在位置:Python中文网/ 问答频道 /正文

给定集合字典:

{1: {2}, 2: {1, 3, 5}, 3: {2, 4}, 4: {3, 7}, 5: {2, 6}, 6: {5}, 7: {8, 4}, 8: {7}}

有没有什么东西我可以很容易地把它变成一本清单字典?你知道吗

期望输出:

{1: [2], 2: [1, 3, 5], 3: [2, 4], 4: [3, 7], 5: [2, 6], 6: [5], 7: [8, 4], 8: [7]}
2条回答
网友
1楼 ·

使用list()函数使用dict comprehension和convert set to list

a = {1: {2}, 2: {1, 3, 5}, 3: {2, 4}, 4: {3, 7}, 5: {2, 6}, 6: {5}, 7: {8, 4}, 8: {7}}
{k:list(v) for k,v in a.items()}
Out[274]: 
{1: [2],
 2: [1, 3, 5],
 3: [2, 4],
 4: [3, 7],
 5: [2, 6],
 6: [5],
 7: [8, 4],
 8: [7]}
网友
2楼 ·
result = {key: list(values) for key, values in dictionary.items()}

相关问题