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.
CodePudding user response:
Your question has nothing to do with json.
sorted()
returns a list, not a dict. Since this list it returns is a list of tuples, and each tuple is a key-value pair for a dictionary, you can create a dict by simply passing this list to dict()
:
with open('test.json', 'r', encoding="utf8") as f:
result_dict = json.load(f)
new_list = sorted(result_dict.items(), key=lambda item: item[1]['amount'], reverse=True)
new_dict = dict(new_list)
Note that sorting a dict is pretty pointless because what does "order" mean in a data structure that has a key and not an index?
CodePudding user response:
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%'}}