[英]How to create a priority list of dictionary
type
之外的所有鍵和值都相同,那么..type
list_ = [
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Owner"
},
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Manager"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Employ"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Manager"
}
]
偏好字典 = {'Owner': 1, 'Manager':2, 'employ':3, 'HR': 4 }
我預期的 output 字典如下
[{'id': '11', 'name': 'son', 'email': 'n@network.com', 'type': 'Owner'},
{'id':'21','name': 'abc','email': 'abc@network.com','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)
您可以簡單地執行src.sort(key = lambda x: preference[x["type"]])
並且您的列表將被排序。
此解決方案按id
對所有元素進行分組,並根據偏好對組進行排序(因此Owner
是第一個, HR
是最后一個),然后從每個組中選擇第一個:
from collections import defaultdict
src = [
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Owner"
},
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Manager"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Employ"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Manager"
}
]
preference = {'Owner': 1, 'Manager':2, 'Employ':3, 'HR': 4 }
d = defaultdict(list)
# group all the records by id
for item in src:
d[item['id']].append(item)
# sort each group by the preference
for item in d.values():
item.sort(key=lambda x: preference[x['type']])
# select only the first from each group
result = [item[0] for item in d.values()]
print(result)
Output:
[{'id': '11', 'name': 'son', 'email': 'n@network.com', 'type': 'Owner'}, {'id': '21', 'name': 'abc', 'email': 'abc@network.com', 'type': 'Manager'}]
您可以創建一個優先級隊列:
from queue import PriorityQueue
priority = {'Owner': 1, 'Manager':2, 'employ':3, 'HR': 4 }
q = PriorityQueue()
for elem in list_:
p = priority[elem['type']]
q.put((p, id(elem), elem))
或者您也可以根據type
對列表進行排序:
priority_list = sorted(list_, key=lambda x: priority[x['type']], reverse=True)
好吧,這是我的鏡頭!
它並不漂亮,但似乎有效。
list_ = [
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Owner"
},
{
"id": "11",
"name": "son",
"email": "n@network.com",
"type": "Manager"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Employ"
},
{
"id": "21",
"name": "abc",
"email": "abc@network.com",
"type": "Manager"
}
]
new = dict( Owner = 0, Manager = 0, Employ = 0, HR = 0 )
for a in list_ :
type_ = a[ 'type' ]
if type_ == 'Owner':
new[ 'Owner' ] += 1
if type_ == 'Manager':
new[ 'Manager' ] += 1
if type_ in [ 'Employ', 'Manager' ]:
new[ 'Employ' ] += 1
new[ 'HR' ] += 1
print( new )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.