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]}
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]}
You don't need to use a dictionary.
You can just use a list and it's indexes since your values are just incrementing numbers.
To convert from a dictionary to a list of it's values, call:
value_list = list(dictionaryname.values())
Then, simply call sort on the list:
value_list.sort()
Also, python dictionaries are an unordered data type.
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]}
Python dict doesn't have a order, it's implemented by hash
and you can not sort it. You should convert it to another type then sort.