python - Sorting multiple dictionary dimensions at once -
i have dictionary of following form:
{ "b":{ "ba": { "score":3, "n":500 }, "aa": { "score": 10, "n":300 }, }, "a":{ "xy": { "score":199, "n":7 }, "zz": { "score":222, "n":55 }, } }
i want first dimension sorted alphabetically, second sorted score
, such when sorted like:
{ "a":{ "zz": { "score":222, "n":55 }, "xy": { "score":199, "n":7 } }, "b":{ "aa": { "score": 10, "n":300 }, "ba": { "score":3, "n":500 } } }
i have searched answer while, have found how sort single dimension in dictionary. best pythonic way go doing this?
after sorting need dump file planning on using json
module for. doing like:
with open("out.json", 'w') fp: json.dump(my_dict, fp, sort_keys=true, indent=4)
you can create appropriate ordereddict
using eg:
ordered = ordereddict( [(k, ordereddict( sorted(v.items(), key=lambda pair: -pair[1]["score"]))) k, v in sorted(data.items())])
now dump json
>>> print(json.dumps(ordered, indent=2)) { "a": { "zz": { "score": 222, "n": 55 }, "xy": { "score": 199, "n": 7 } }, "b": { "aa": { "score": 10, "n": 300 }, "ba": { "score": 3, "n": 500 } } }
note: use reverse=true
inside inner sort instead of negating score, depends how feel ...
Comments
Post a Comment