簡體   English   中英

Python - 計算項目並將其添加到新字典中

[英]Python - Counting and adding items to a new dictionary

我有一個包含很多條目的列表,如下所示:

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.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},
]

所以我們可以使用itertools.groupby來達到想要的效果。 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}]

一個可能的解決方案,不使用外部庫:

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()]

您可以首先創建字典字典:

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

現在您需要做的就是將其轉換為列表:

second_list = list(dict_1.values())

您可以將集合模塊中的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()]

輸出:

[{'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM