Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a priority list of dictionary

  • list is below
  • preference dictionary is below
  • if all the keys and values except type will be same then ..
  • Need to compare type in each list which is highest order in preference dictionary
  • Output is list of dictionary which type is highest order
list_ = [
  {
    "id": "11",
    "name": "son",
    "email": "[email protected]",
    "type": "Owner"
  },
      {
    "id": "11",
    "name": "son",
    "email": "[email protected]",
    "type": "Manager"
  },
{
    "id": "21",
    "name": "abc",
    "email": "[email protected]",
    "type": "Employ"
  },
{
    "id": "21",
    "name": "abc",
    "email": "[email protected]",
    "type": "Manager"
  }
]

A preference dictionary = {'Owner': 1, 'Manager':2, 'employ':3, 'HR': 4 }

My expected output dictionary below

[{'id': '11', 'name': 'son', 'email': '[email protected]', 'type': 'Owner'},
{'id':'21','name': 'abc','email': '[email protected]','type': 'Manager'}]

new_list = []
for each in list_:
    if each['type'] in priority.keys():
        if each['id'] not in new_list:
            new_list.append(each)
like image 766
sim Avatar asked Mar 01 '23 15:03

sim


1 Answers

You can simply do src.sort(key = lambda x : preference[x["type"]]) and your list will be sorted.

like image 104
Harshit Gupta Avatar answered Mar 27 '23 04:03

Harshit Gupta