【问题标题】:Python - Merging 3 different dictionary and grouping the outputPython - 合并 3 个不同的字典并对输出进行分组
【发布时间】:2022-07-07 17:09:13
【问题描述】:

我在 python 中创建了 3 个不同的字典,但是我相信这不能合并到 1 个字典中,例如NewDict 由于所有 3 个中的相同键,例如姓名和公司。

NewDict1 =  {'Name': 'John,Davies', 'Company': 'Google'}
NewDict2 =  {'Name': 'Boris,Barry', 'Company': 'Microsoft'}
NewDict3 =  {'Name': 'Humphrey,Smith', 'Company': 'Microsoft'}

我想在上面进行分组,使我的输出如下:

谷歌:约翰戴维斯微软:鲍里斯巴里,汉弗莱史密斯

任何帮助将不胜感激。

【问题讨论】:

    标签: python


    【解决方案1】:

    使用defaultdict

    from collections import defaultdict
    
    dicts = [NewDict1, NewDict2, NewDict3]
    
    out = defaultdict(list)
    
    for d in dicts:
        out[d['Company']].append(d['Name'])
        
    dict(out)
    

    输出:{'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      相关资源
      最近更新 更多