【问题标题】:Merge dictionaries if value of a particular key is same如果特定键的值相同,则合并字典
【发布时间】:2018-10-30 20:29:58
【问题描述】:

例如,我有四个字典列表,如

[{'username': 'xyz', 'label':'chemistry', 'marks': 56},
 {'username': 'abc', 'label':'chemistry', 'marks': 95},
 {'username': 'xyz', 'label':'math', 'marks': 43},
 {'username': 'abc', 'label':'math', 'marks': 87}]

我想转换数据,以便我可以得到数据

[{'username': 'xyz', 'chemistry': 56, 'math': 43},
 {'username': 'abc', 'chemistry': 95, 'math': 87}]

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    使用collections.defaultdict

    from collections import defaultdict
    
    L = [{'username': 'xyz', 'label':'chemistry', 'marks': 56},
         {'username': 'abc', 'label':'chemistry', 'marks': 95},
         {'username': 'xyz', 'label':'math', 'marks': 43},
         {'username': 'abc', 'label':'math', 'marks': 87}]
    
    dd = defaultdict(lambda: defaultdict(int))
    
    for i in L:
        dd[i['username']][i['label']] = i['marks']
    
    res = [{'username': k, **v} for k, v in dd.items()]
    
    [{'username': 'xyz', 'chemistry': 56, 'math': 43},
     {'username': 'abc', 'chemistry': 95, 'math': 87}]
    

    【讨论】:

      【解决方案2】:

      这是一个一次性解决方案,使用 dict 映射来跟踪每个用户名的列表条目(假设您的 dicts 列表存储在变量 l 中):

      m = []
      d = {}
      for i in l:
          u = i['username']
          if u not in d:
              m.append({'username': u})
              d[u] = m[-1]
          d[u][i['label']] = i['marks']
      

      m 将变为:

      [{'username': 'xyz', 'chemistry': 56, 'math': 43}, {'username': 'abc', 'chemistry': 95, 'math': 87}]
      

      【讨论】:

        【解决方案3】:

        这有点冗长,但可以完成工作。

        usersDict = {}
        for item in listOfDicts:
            if (item['username'] in dict):
                usersDict[item['username']][item['label']] = item['marks']
            else:
                usersDict[item['username']] = { 
                    'username': item['username']
                    item['label']: item['marks'] 
                }
        result = list(userDict.values())
        

        请注意,我在这里使用字典,因为在字典上查找是 O(1) 而不是在列表上的 O(n)。

        【讨论】:

          猜你喜欢
          • 2020-05-03
          • 1970-01-01
          • 2013-02-24
          • 2018-08-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-29
          相关资源
          最近更新 更多