[英]Creating multiple dictionaries based on other dictionary values in python
我有一个包含许多词典的列表。 每个字典表示我的应用程序中发生的更改。 “更改”字典具有以下条目:
userid: The user ID for a user
ctype: A reference to a change type in my application
score: A score
ctype可以是大约12种不同的字符串之一,以包括“删除”,“新”,“编辑”等。 这是“更改”词典之一的示例:
{'userid':2, 'score':10, 'ctype':'edit'}
我的问题是,如何创建一个字典,将汇总这个庞大词典列表中每个用户的所有更改类型? 我想从每个更改字典中添加分数以创建总分数,并将每个ctype实例添加在一起以获取每个实例的计数。 目的是要有一个字典列表,每个字典看起来像这样:
{'userid':2, 'score':325, 'deletion':2, 'new':4, 'edit':9}
我一直在尝试解决这个问题,但是我对python还是很陌生,我不确定如何计算实际的更改类型。 让我着迷的另一部分是如何基于“ userid”引用字典。 如果有人可以给出答案,我相信所有这些对我来说都是非常明显的。 我感谢所有帮助。
在这里汇总数据的关键是要有一个字典,其中每个键都是用户ID,每个条目都是与该用户ID相关的数据。
final_data = {}
for entry in data:
userid = entry["userid"]
if userid not in final_data:
final_data[userid] = {"userid": userid, "score": 0}
final_data[userid]["score"] += entry["score"]
if not entry["ctype"] in final_data[userid]:
final_data[userid][entry["ctype"]] = 1
else:
final_data[userid][entry["ctype"]] += 1
如果要将结果作为字典列表,则只需使用final_data.values()
你能有
(模拟不是真正的python。)
{userid : {score : 1, ctype : ''}}
您可以将dict的值嵌套在python词典中。
要相对于userid
索引字典,可以使用字典词典:
from collections import defaultdict
dict1 = {'userid': 1, 'score': 10, 'ctype': 'edit'}
dict2 = {'userid': 2, 'score': 13, 'ctype': 'other'}
dict3 = {'userid': 1, 'score': 1, 'ctype': 'edit'}
list_of_dicts = [dict1, dict2, dict3]
user_dict = defaultdict(lambda: defaultdict(int))
for d in list_of_dicts:
userid = d['userid']
user_dict[userid]['score'] += d['score']
user_dict[userid][d['ctype']] += 1
# user_dict is now
# defaultdict(<function <lambda> at 0x02A7DF30>,
# {1: defaultdict(<type 'int'>, {'edit': 2, 'score': 11}),
# 2: defaultdict(<type 'int'>, {'score': 13, 'other': 1})})
在示例中,我使用defaultdict
来避免在每次迭代时检查键d['ctype']
存在。
它可能看起来像这样:
change_types = ['deletion', 'new', 'edit', ...]
user_changes = {}
for change in change_list:
userid = change['userid']
if not userid in user_changes:
aggregate = {}
aggregate['score'] = 0
for c in change_types:
aggregate[c] = 0
aggregate['userid'] = userid
user_changes[userid] = aggregate
else:
aggregate = user_changes[userid]
change_type = change['ctype']
aggregate[change_type] = aggregate[change_type] + 1
aggregate['score'] = aggregate['score'] + change['score']
实际上,为聚合创建一个类是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.