我有以下包含工作名称,数量和城市名称的词典列表
question = [{
"count": 2,
"city": "Pune",
"job_NAME": "clerk"
}, {
"count": 1,
"city": "kolkata",
"job_NAME": "manager"
}, {
"count": 2,
"city": "Mumbai",
"job_NAME": "accountant"
}, {
"count": 1,
"city": "New Delhi",
"job_NAME": "clerk"
}]
我要的是,如果job_name在这种情况下为“职员”,则计数和城市必须在键“ jobs”下的一个列表中
answer = [{
"job_name": "clerk",
"jobs": [{
"city": "pune",
"count": 2
}, {
"city": "New Delhi",
"count": 1
}]
}, {
"job_name": "manager",
"jobs": [{
"city": "kolkata",
"count": 1
}]
}, {
"job_name": "accountant",
"jobs": [{
"city": "Mumbai",
"count": 2
}]
}]
如果问题列表中有任何重复的工作档案,在这种情况下,请查询其所在城市,并将计数添加到“工作”键列表中。
我将非常感谢您提供的任何帮助!
预先感谢
答案 0 :(得分:1)
使用collections.defaultdict
例如:
from collections import defaultdict
d = defaultdict(list)
question = [{'count': 2, 'city': 'Pune', 'job_NAME': 'clerk'}, {'count': 1, 'city': 'kolkata', 'job_NAME': 'manager'}, {'count': 2, 'city': 'Mumbai', 'job_NAME': 'accountant'}, {'count': 1, 'city': 'New Delhi', 'job_NAME': 'clerk'}]
for i in question:
d[i["job_NAME"]].append({"city": i["city"], "count": i["count"]})
answer = [{"job_name": k, "jobs": v} for k, v in d.items()]
print(answer)
输出:
[{'job_name': 'clerk',
'jobs': [{'city': 'Pune', 'count': 2}, {'city': 'New Delhi', 'count': 1}]},
{'job_name': 'accountant', 'jobs': [{'city': 'Mumbai', 'count': 2}]},
{'job_name': 'manager', 'jobs': [{'city': 'kolkata', 'count': 1}]}]
答案 1 :(得分:1)
我先使用defaultdict(list)
对输入列表中的条目进行分组,然后在第二次迭代中设置结果:
from collections import defaultdict
groups = defaultdict(list)
for jobs in question:
job_name = jobs["job_NAME"]
del jobs["job_NAME"]
groups[job_name].append(jobs)
answer = [
dict(job_name=job_name, jobs=jobs) for job_name, jobs in groups.items()
]
# alternative with classic loop
answer = []
for job_name, jobs in groups.items():
answer.append(dict(job_name=job_name, jobs=jobs))
答案 2 :(得分:0)
单线:
from itertools import groupby
from operator import itemgetter
answer = [{'job_name': k, 'jobs': [{f: v for f, v in d.items() if f != 'job_NAME'} for d in g]}
for k, g in groupby(sorted(question, key=itemgetter('job_NAME')), key=itemgetter('job_NAME'))]
结果:
[{'job_name': 'accountant', 'jobs': [{'count': 2, 'city': 'Mumbai'}]},
{'job_name': 'clerk',
'jobs': [{'count': 2, 'city': 'Pune'}, {'count': 1, 'city': 'New Delhi'}]},
{'job_name': 'manager', 'jobs': [{'count': 1, 'city': 'kolkata'}]}]
按question
对job_NAME
进行排序和分组,然后使用job_name
和jobs
将答案构造为字典列表。