我有一个包含很多条目的列表,看起来像这样:
first_list = [
{'manager': 'manager1', 'template_id': '12345', 'template_title': 'Template Title1'},
{'manager': 'manager2', 'template_id': '12346', 'template_title': 'Template Title2'},
{'manager': 'manager23', 'template_id': '12345', 'template_title': 'Template Title1'}]
我想计算一个template_id在列表中的次数,然后将其添加到新的词典列表中(或者,如果有更好的方法可以做到这一点,我非常高兴)。
因此最终结果将是:
second_list = [
{'template_id': '12345', , 'template_title': 'Template Title1', 'count': '5'},
{'template_id': '12346', , 'template_title': 'Template Title2', 'count': '3'},
{'template_id': '12347', , 'template_title': 'Template Title3', 'count': '4''}]
我不确定如何正确地遍历此过程以获取template_id的计数。任何帮助,我们将不胜感激。谢谢!
您可以使用itertools.groupby按template_id对列表进行排序,按template_id对组项目进行排序,如下所示:
import itertools
import operator
first_list = [
{"manager": "manager1", "template_id": "12345", "template_title": "Template Title1"},
{"manager": "manager2", "template_id": "12346", "template_title": "Template Title2"},
{"manager": "manager23", "template_id": "12345", "template_title": "Template Title1"},
]
get_template_id = operator.itemgetter("template_id")
first_list.sort(key=get_template_id)
second_list = []
for template_id, group in itertools.groupby(first_list, key=get_template_id):
group = list(group)
first = group[0]
entry = {
"template_id": template_id,
"template_title": first["template_title"],
"count": len(group),
}
second_list.append(entry)
print(second_list)
你得到:
[
{'template_id': '12345', 'template_title': 'Template Title1', 'count': 2},
{'template_id': '12346', 'template_title': 'Template Title2', 'count': 1},
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句