'Sort a JSON file by value and return it as a dictionary python

I would like to open a JSON file, sort it in ascending order by the 'amount' key and return it as a dictionary. I have tried many other solutions on this website and none of them seemed to have worked.

My code:

with open('test.json', 'r', encoding="utf8") as f:  
    result_dict = json.load(f)
    new_dict = sorted(result_dict.items(), key=lambda item: item[1]['amount'], reverse=True)

'test.json'

{"feel": {"amount": 54, "per": "0.20952%"}, "like": {"amount": 145, "per": "0.5626%"}, "so": {"amount": 83, "per": "0.32203%"}}

When I run my code above, the output I get is:

[('like', {'amount': 145, 'per': '0.5626%'}), ('so', {'amount': 83, 'per': '0.32203%'}), ('feel', {'amount': 54, 'per': '0.20952%'})]

The intended output I would like is:

{'like': {'amount': 145, 'per': '0.5626%'}, 'so': {'amount': 83, 'per': '0.32203%'}, 'feel': {'amount': 54, 'per': '0.20952%'}}

Any help is greatly appreciated.



Solution 1:[1]

Running your code and getting differnet result made me a little bit confused. But what I have come up with is pretty close to your code with a little bit of edit:

import json
data = json.loads('{"feel": {"amount": 54, "per": "0.20952%"}, "like": {"amount": 145, "per": "0.5626%"}, "so": {"amount": 83, "per": "0.32203%"}}')
sortedKeys = sorted(data, key=lambda item: data[item]["amount"], reverse=True)
resultDict = {}
for value in sortedKeys:
  resultDict[value] = data[value]
print(resultDict)

Output

{'like': {'amount': 145, 'per': '0.5626%'}, 'so': {'amount': 83, 'per': '0.32203%'}, 'feel': {'amount': 54, 'per': '0.20952%'}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1