how can i sort python dict to nested list based on

2020-05-09 17:55发布

问题:

I have a nested dictionary

 d = {'records':[
       {'name':abhi,'age':23,'dept':'cse'}, 
       {'name':anu,'age':20,'dept':'ece'},
       {'name':ammu,'age':25,'dept':'cse'},
       {'name':anju,'age':26,'dept':'ece'}
     ]}

but I want to have the dictionary rearranged, grouped by department. I have done different methods, but did not get the desired result.

d = [
      [ {'name':abhi,'age':23,'dept':'cse'},
        {'name':ammu,'age':25,'dept':'cse'}
      ],
      [ {'name':anu,'age':20,'dept':'ece'},
        {'name':anju,'age':26,'dept':'ece'}
      ]
    ]

Any help would be appreciated.

回答1:

What you have is a list of dictionaries within a dictionary. You can sort these dictionaries using standard list sorting methods:

d={'records':[{'name':'abhi','age':23,'dept':'cse'}, 
              {'name':'anu','age':20,'dept':'ece'},
              {'name':'ammu','age':25,'dept':'cse'},
              {'name':'anju','age':26,'dept':'ece'}]}

d['records'].sort(key = lambda x: x['name'])

>>> d['records']
[{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}, {'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}]

For your particular case:

d['records'].sort(key = lambda x: (x['name'], x['dept']))

And then a list comprehension to group sublists with the same dept together:

my_list = [[i for i in d['records'] if i['dept'] == de] for de in {i['dept'] for i in d['records']}]

>>> my_list
[[{'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}], [{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}]]


标签: python arrays