pythondictionarykeykey-valueitems

How can I arrange a dictionary using python so that the values are represented from lowest to highest order?


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.


Solution

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