【问题标题】:Creating multiple dictionaries based on other dictionary values in python根据python中的其他字典值创建多个字典
【发布时间】:2011-03-04 12:14:41
【问题描述】:

我有一个包含许多字典的列表。每个字典都代表我的应用程序中发生的变化。 “更改”字典具有以下条目:

userid: The user ID for a user
ctype: A reference to a change type in my application
score: A score

ctype 可以是大约 12 个不同的字符串之一,包括“deletion”、“new”、“edit”等。以下是“更改”字典之一的示例:

{'userid':2, 'score':10, 'ctype':'edit'}

我的问题是,如何创建一个字典来汇总这个庞大字典列表中每个用户的所有更改类型?我想添加每个更改字典中的分数以创建总分,并将每个 ctype 实例加在一起以获得每个实例的计数。目标是有一个字典列表,每个字典看起来像这样:

{'userid':2, 'score':325, 'deletion':2, 'new':4, 'edit':9}

我一直在尝试解决这个问题,但我对 python 还很陌生,我不确定如何计算实际的更改类型。让我印象深刻的另一部分是如何根据“userid”引用字典。如果有人能给出答案,我相信所有这些对我来说都会变得非常明显。我感谢任何和所有的帮助。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    这里聚合数据的关键是要有一个字典,其中每个键都是用户 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()

    【讨论】:

      【解决方案2】:

      可以吗

      (模拟不是真正的python。)

      {userid : {score : 1, ctype : ''}}
      

      您可以将字典作为值嵌套在 python 字典中。

      【讨论】:

        【解决方案3】:

        它可能看起来像这样:

        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']
        

        实际上为聚合创建一个类是个好主意。

        【讨论】:

          【解决方案4】:

          要索引与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'] 是否存在。

          【讨论】:

          • 首选userid in user_dict 而不是has_key
          • 你也可以user_dict = defaultdict(lambda: defaultdict(int))
          猜你喜欢
          • 2018-04-07
          • 2019-02-23
          • 2012-01-18
          • 1970-01-01
          • 2018-04-30
          • 1970-01-01
          • 2010-11-15
          • 1970-01-01
          • 2018-03-27
          相关资源
          最近更新 更多