Reputation: 519
i have a dictionary as below :
{' PLATINUM': [{'Name': 'MATH',
'Description': 'You can earn up to 50 Rs per year',
'value': 50},
{'Name': 'SCIENCE',
'Description': 'You can earn up to 100 Rs per year',
'value': 100},
{'Name': 'TOTAL',
'Description': 'You can earn up to 200 Rs per year',
'value': 200},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 50 Rs per year',
'value': 50}],
'TITANIUM': [{'Name': 'SOCIAL',
'Description': 'You can earn up to 20 Rs per year',
'value': 20},
{'Name': 'MATH',
'Description': 'You can earn up to 10 Rs per year',
'value': 10},
{'Name': 'TOTAL',
'Description': 'You can earn up to 30 Rs per year',
'value': 30}]}
I wanted it to be sorted at each level - 'PLATINUM','TITANIUM' (as many levels) with the 'value'. so expected dictionary will look like :
{' PLATINUM': [
{'Name': 'TOTAL',
'Description': 'You can earn up to 200 Rs per year',
'value': 200},
{'Name': 'SCIENCE',
'Description': 'You can earn up to 100 Rs per year',
'value': 100},
{'Name': 'MATH',
'Description': 'You can earn up to 50 Rs per year',
'value': 50},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 50 Rs per year',
'value': 50}],
'TITANIUM': [
{'Name': 'TOTAL',
'Description': 'You can earn up to 30 Rs per year',
'value': 30}
{'Name': 'SOCIAL',
'Description': 'You can earn up to 20 Rs per year',
'value': 20},
{'Name': 'MATH',
'Description': 'You can earn up to 10 Rs per year',
'value': 10}]}
Can any one help me to achieve it with python code ?
Upvotes: 0
Views: 48
Reputation: 88305
You could use the following dictionary comprehension, where the inner dictionaries are sorted
according to the key value
:
from operator import itemgetter
d = {' PLATINUM': [{'Name': 'MATH', 'Description': 'You ...'}
{k:sorted(d[k], key=itemgetter('value'), reverse=True) for k in d}
Output
{' PLATINUM': [{'Name': 'TOTAL',
'Description': 'You can earn up to 200 Rs per year',
'value': 200},
{'Name': 'SCIENCE',
'Description': 'You can earn up to 100 Rs per year',
'value': 100},
{'Name': 'MATH',
'Description': 'You can earn up to 50 Rs per year',
'value': 50},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 50 Rs per year',
'value': 50}],
'TITANIUM': [{'Name': 'TOTAL',
'Description': 'You can earn up to 30 Rs per year',
'value': 30},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 20 Rs per year',
'value': 20},
{'Name': 'MATH',
'Description': 'You can earn up to 10 Rs per year',
'value': 10}]}
Upvotes: 1