0

I have the following dictionary:

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}

How can I rearrange the dictionary to organize the values from lowest to highest order? I am expecting to have the following output after rearranging the dictionary based on the values:

d = {'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8,}}

I tried to use the sorted option, d = sorted(d.items()), but it sorts the dictionary based on the keys.

Guy
  • 46,488
  • 10
  • 44
  • 88
pr_kr1993
  • 185
  • 6
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – ewokx Jun 06 '23 at 05:35
  • I did try the following: d = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}, but it doesn't work. I get a TypeError – pr_kr1993 Jun 06 '23 at 05:41

2 Answers2

1
d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}
sorted_dict = {i:dict(sorted(d[i].items(),key=lambda x:x[1])) for i in d.keys()}

I know that it's pretty hard to read, so I will try to explain what I can. Basically, you are using the sorted function which takes an iterable and a function of one argument which tells the sorted function to sort the iterable on the basis of that lambda function.

Edit: I forgot to show the output.

{'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8}}
vertical
  • 53
  • 6
0

The solution from your comment was on the right direction, you just need to sort the inner dicts with a loop and not the outer dict

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in d.items()}

after that you can also sort the outer dictionary if needed

d = dict(sorted(d.items()))

Everything in a single dict-comprehension

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in sorted(d.items())}
Guy
  • 46,488
  • 10
  • 44
  • 88