RGPython
RGPython

Reputation: 27

Turn Dictionary of Sets into Dictionary of Lists

Given the Dictionary of Sets:

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

Is there anyway I can easily turn it into a Dictionary of Lists?

Desired Output:

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

Upvotes: 1

Views: 249

Answers (2)

Allen Qin
Allen Qin

Reputation: 19947

Use dict comprehension and convert set to list using the list() function

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

Upvotes: 0

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

result = {key: list(values) for key, values in dictionary.items()}

Upvotes: 1

Related Questions