Home > Mobile >  dictionary inside dictionary sorting
dictionary inside dictionary sorting

Time:05-11

this is the dict i need to sort it by "error" value

{'mdouglas': {'INFO': 2, 'ERROR': 3}, 'noel': {'INFO': 6, 'ERROR': 3}, 'breee': {'INFO': 1, 'ERROR': 5}, 'ac': {'INFO': 2, 'ERROR': 2}, 'blossom': {'INFO': 2, 'ERROR': 6}, 'rr.robinson': {'INFO': 2, 'ERROR': 1}, 'mcintosh': {'INFO': 4, 'ERROR': 3}, 'jackowens': {'INFO': 2, 'ERROR': 4}, 'oren': {'INFO': 2, 'ERROR': 7}, 'xlg': {'INFO': 0, 'ERROR': 4}, 'ahmed.miller': {'INFO': 2, 'ERROR': 4}, 'bpacheco': {'INFO': 0, 'ERROR': 2}, 'enim.non': {'INFO': 2, 'ERROR': 3}, 'flavia': {'INFO': 0, 'ERROR': 5}, 'sri': {'INFO': 2, 'ERROR': 2}, 'nonummy': {'INFO': 2, 'ERROR': 3}, 'britanni': {'INFO': 1, 'ERROR': 1}, 'montanap': {'INFO': 0, 'ERROR': 4}, 'mai.hendrix': {'INFO': 0, 'ERROR': 3}, 'kirknixon': {'INFO': 2, 'ERROR': 1}}

CodePudding user response:

This does the job,

errors = [(key, data[key]["ERROR"]) for key in data.keys()] #data here is the dictionary
snorted_keys = sorted(errors, key = lambda item:item[-1])
snorted_dict = list(map(lambda item:(item[0], data[item[0]]), snorted_keys))

Output -

[('rr.robinson', {'ERROR': 1, 'INFO': 2}),
 ('britanni', {'ERROR': 1, 'INFO': 1}),
 ('kirknixon', {'ERROR': 1, 'INFO': 2}),
 ('ac', {'ERROR': 2, 'INFO': 2}),
 ('bpacheco', {'ERROR': 2, 'INFO': 0}),
 ('sri', {'ERROR': 2, 'INFO': 2}),
 ('mdouglas', {'ERROR': 3, 'INFO': 2}),
 ('noel', {'ERROR': 3, 'INFO': 6}),
 ('mcintosh', {'ERROR': 3, 'INFO': 4}),
 ('enim.non', {'ERROR': 3, 'INFO': 2}),
 ('nonummy', {'ERROR': 3, 'INFO': 2}),
 ('mai.hendrix', {'ERROR': 3, 'INFO': 0}),
 ('jackowens', {'ERROR': 4, 'INFO': 2}),
 ('xlg', {'ERROR': 4, 'INFO': 0}),
 ('ahmed.miller', {'ERROR': 4, 'INFO': 2}),
 ('montanap', {'ERROR': 4, 'INFO': 0}),
 ('breee', {'ERROR': 5, 'INFO': 1}),
 ('flavia', {'ERROR': 5, 'INFO': 0}),
 ('blossom', {'ERROR': 6, 'INFO': 2}),
 ('oren', {'ERROR': 7, 'INFO': 2})]
  • Related