-2

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]}
Bala
  • 648
  • 5
  • 15
  • It can be sorted by a nice trick. Try here: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – seslak Oct 02 '22 at 01:49
  • https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – seslak Oct 02 '22 at 01:51

3 Answers3

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.

Craze XD
  • 110
  • 8
1

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]}
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
-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.

wityu
  • 68
  • 1
  • 4
  • 1
    From Python 3.6+ [dicts do have an order](https://stackoverflow.com/a/39980744/5287638), but you are correct that you cannot sort them. (Using `sorted()` on a dict produces a sorted list of values.) – Jack Taylor Oct 02 '22 at 02:00