how can i sort python dict to nested list based on key value

前端 未结 1 1098
鱼传尺愫
鱼传尺愫 2021-01-29 09:57

I have a nested dictionary

 d = {\'records\':[
       {\'name\':abhi,\'age\':23,\'dept\':\'cse\'}, 
       {\'name\':anu,\'age\':20,\'dept\':\'ece\'},
       {\         


        
1条回答
  •  日久生厌
    2021-01-29 10:47

    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'}]]
    

    0 讨论(0)
提交回复
热议问题