Issue
How can I sort the following dictionary by its values and rearrange keys?.
{1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 1, 1, 1], 4: [1, 0, 1, 1]}
Expected result :
{1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 0, 1, 1], 4: [1, 1, 1, 1]}
Solution
The easiest way is to create a new dictionary by combining the keys and the sorted values from the original dict
.
Assign that dict to the original variable, and you're done.
In [1]: orig = {1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 1, 1, 1], 4: [1, 0, 1, 1]}
Out[1]: {1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 1, 1, 1], 4: [1, 0, 1, 1]}
In [2]: k = list(orig.keys())
Out[2]: [1, 2, 3, 4]
In [3]: v = sorted(orig.values())
Out[3]: [[0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
In [4]: orig = dict(zip(k, v))
Out[4]: {1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 0, 1, 1], 4: [1, 1, 1, 1]}
It can even be done in a single line:
In [1]: orig = {1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 1, 1, 1], 4: [1, 0, 1, 1]};
In [2]: orig = dict(zip(orig.keys(), sorted(orig.values())))
Out[2]: {1: [0, 0, 1, 1], 2: [0, 1, 1, 1], 3: [1, 0, 1, 1], 4: [1, 1, 1, 1]}
Answered By - Roland Smith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.