[英]Python - Counting and adding items to a new dictionary
I have a list with quite a few entries that looks like this:我有一个包含很多条目的列表,如下所示:
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'}]
I want to count how many times a template_id is in the list, then add those to a new list of dictionaries (or if there is a better way to do this, I'm all ears).我想计算一个 template_id 在列表中的次数,然后将它们添加到新的字典列表中(或者如果有更好的方法来做到这一点,我全神贯注)。
So end result would be:所以最终结果将是:
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''}]
I'm not sure how to iterate through this properly to get the count of the template_id.我不确定如何正确地遍历它以获取 template_id 的计数。 Any help is greatly appreciate.
非常感谢任何帮助。 Thank you!
谢谢!
You can sort the list by template_id and the group items by template_id using itertools.groupby , like this:您可以使用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)
You get:你得到:
[
{'template_id': '12345', 'template_title': 'Template Title1', 'count': 2},
{'template_id': '12346', 'template_title': 'Template Title2', 'count': 1},
]
So we can use itertools.groupby
to achieve the desired result.所以我们可以使用
itertools.groupby
来达到想要的效果。 The caveat for itertools.groupby
is that your data must be pre-sorted on the grouped keys. itertools.groupby
的警告是您的数据必须按分组键进行预排序。
TO_KEEP = ['template_id', 'template_title']
def sort_key(item):
return [item.get(k) for k in TO_KEEP]
results = []
sorted_data = sorted(first_list, key=sort_key)
for k, v in itertools.groupby(sorted_data, key=sort_key):
temp = dict(zip(TO_KEEP, k))
temp.update({'count': len(list(v))})
results.append(temp)
print(results)
[{'template_id': '12345', 'template_title': 'Template Title1', 'count': 2},
{'template_id': '12346', 'template_title': 'Template Title2', 'count': 1}]
A possible solution, without utilizing external libraries:一个可能的解决方案,不使用外部库:
counts = {}
for d in first_list:
key = (d['template_id'], d['template_title'])
counts[key] = counts.get(key, 0) + 1
second_list = [{'template_id': k[0], 'template_title': k[1], 'counts': v} for k, v in counts.items()]
You can do this ny first creating a dictionary of dictionaries:您可以首先创建字典字典:
dict_1 = {}
for sub_dict in first_list:
template_id = sub_dict['template_id']
template_title = sub_dict['template_title']
if template_id not in dict_1:
dict_1[template_id] = {'template_id' : template_id, 'template_title': template_title, 'count' : 0}
dict_1[template_id]['count'] += 1
Now all you need to do is convert this to a list:现在您需要做的就是将其转换为列表:
second_list = list(dict_1.values())
you could use Counter
from collections module with list comprehension:您可以将集合模块中的
Counter
与列表理解一起使用:
from collections import Counter
count = Counter([e['template_id'] for e in first_list])
id_title = {e['template_id']: e['template_title'] for e in first_list}
second_list = [{'template_id': i, 'template_title': id_title[i], 'count': c} for i, c in count.items()]
output:输出:
[{'template_id': '12345', 'template_title': 'Template Title1', 'count': 2},
{'template_id': '12346', 'template_title': 'Template Title2', 'count': 1}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.