Python-计算项目并将其添加到新字典中

我有一个包含很多条目的列表,看起来像这样:

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的计数。任何帮助,我们将不胜感激。谢谢!

劳伦·拉波特(Laurent LAPORTE)

您可以使用itertools.groupbytemplate_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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

计算列表并添加到新字典(Python)

将新字典添加到字典python列表中

Python更新字典并使用循环将其添加到列表末尾

通过一个键获取多键字典的总和并将其添加到Python中的datfarme列中?

在Python中将新项目添加到字典中

在python中将项目添加到字典中(嵌套)

更新字典中的列表添加到每个键 Python3 中的列表

如何从SQL查询中提取单个列并将其添加到Python中的列表中

拆分列表,提取元素并将其添加到python中

线程轮询sqs并将其添加到python队列中以处理模具

如何使用python选择特定的列表元素并将其添加到csv行中

如何创建命令并将其添加到 python 存储库中的路径

Python:使用旧项目将新项目添加到列表的字典中

python:如何溢出字典并将信息添加到数据框中的行?

动态地将属性添加到指向字典中项目的Python类中

如何在 Python 中将列表中的项目添加到字典中,

使用python中的循环将项目添加到现有字典中

转换字典中的2元组键,并将其作为字典值添加到新字典中

循环时将项目添加到Python字典

如何在Python的for循环中将项目添加到字典中?

将具有公共密钥的项目添加到python中的字典

如何提取python中的形式化Java方法参数并将其添加到字符串列表中?

确定numpy数组中的重复值并将其添加到另一列python中

如何从其余数据集中选择一行并将其添加到python中的初始矩阵中?

在Python 3.7中一步就初始化并将值添加到字典中的列表

根据值对python中的字典列表进行排序,并将排序后的对象添加到新列表中

使用python 3.x时,如何从“ for”命令获取输出并将其添加到列表或字符串中?

如何查找文件中所有出现的特殊字符并将其添加到python列表中

在python中的选项卡定界文本文件中选择列并将其添加到tsv文件