合并到不同的词典

时间:2016-04-29 11:03:33

标签: python list python-2.7 dictionary

我有两个这样的词典列表:

dic1 = [{'Age': 8, 'Pets Name': 'Felix', 'Species': 'Cat'}, {'Age': 57, 'Pets Name': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': 12, 'Pets Name': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Pets Name': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Pets Name': 'Leonardo', 'Species': 'Tortoise'}, {'Age': 9, 'Pets Name': 'Milo', 'Species': 'Dog'}, {'Age': 57, 'Pets Name': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Pets Name': 'Dory', 'Species': 'Fish'}]
dic2 = [{'Pets Names': 'Michelangelo', "Owner's Names": 'Ana'}, {'Pets Names': 'Dory', "Owner's Names": 'Eva'}, {'Pets Names': 'Rantanplan', "Owner's Names": 'Ada'}, {'Pets Names': 'Leonardo', "Owner's Names": 'Ana'}, {'Pets Names': 'Felix', "Owner's Names": 'Eva'}, {'Pets Names': 'Raphael', "Owner's Names": 'Ana'}, {'Pets Names': 'Nemo', "Owner's Names": 'Eva'}]

我需要制作第三个字典列表,作为所有者姓名的键(字典),以及各自宠物的年龄值。例如,给定上面的两个列表,输出应为:

dic3 = [{'Ana': [57, 45, 57]}, {'Eva': [4, 8, 2]}, {'Ada': [12]}]

主要目标是获得每个所有者的宠物年龄的平均值,但我想我可以在拥有所需的词典后自己完成。 到目前为止我只有这个:

def merge_dicts(dic1,dic2):

   name = [li['Pets Name'] for li in dic1]
   age = [li['Age'] for li in dic1]
   owenrsName = [li["Owner's Names"] for li in dic2]

这为我提供了宠物名称,年龄和所有者姓名的列表,但我不知道它是否与最终功能相​​关。< / p>

提前致谢。

4 个答案:

答案 0 :(得分:3)

dic1 = [{'Age': 8, 'Pets Name': 'Felix', 'Species': 'Cat'}, {'Age': 57, 'Pets Name': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': 12, 'Pets Name': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Pets Name': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Pets Name': 'Leonardo', 'Species': 'Tortoise'}, {'Age': 9, 'Pets Name': 'Milo', 'Species': 'Dog'}, {'Age': 57, 'Pets Name': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Pets Name': 'Dory', 'Species': 'Fish'}]
dic2 = [{'Pets Names': 'Michelangelo', "Owner's Names": 'Ana'}, {'Pets Names': 'Dory', "Owner's Names": 'Eva'}, {'Pets Names': 'Rantanplan', "Owner's Names": 'Ada'}, {'Pets Names': 'Leonardo', "Owner's Names": 'Ana'}, {'Pets Names': 'Felix', "Owner's Names": 'Eva'}, {'Pets Names': 'Raphael', "Owner's Names": 'Ana'}, {'Pets Names': 'Nemo', "Owner's Names": 'Eva'}]



def merge_dicts(dic1,dic2):
    dict3= {}
    result = []
    name = [li['Pets Name'] for li in dic1]
    age = [li['Age'] for li in dic1]
    owenrsName = [li["Owner's Names"] for li in dic2]


    for d2 in dic2:

       pname = d2['Pets Names']
       oname = d2["Owner's Names"]

       if oname not in dict3:
            dict3[oname] = []

       for d1 in dic1:
           if d1['Pets Name'] == pname:
               dict3[oname].append(d1['Age'])
    for key,value in dict3.items():
        result.append({key:value})

    print(result)


merge_dicts(dic1,dic2)

O / P

[{'Ada': [12]}, {'Eva': ['4', 8, '2']}, {'Ana': [57, '45', 57]}]

答案 1 :(得分:2)

您可以使用简单的理解:

{ name : [ d['Age'] for d in dic1 if d['Pets Name']
          in [ d2['Pets Names'] for d2 in dic2 if d2["Owner's Names"] == name ] ]
      for name in set(( d["Owner's Names"] for d in dic2)) }

答案 2 :(得分:2)

使用一些快捷方式:

def merge_dicts(dic1,dic2):
    ages = { li['Pets Name']:li['Age'] for li in dic1 }
    owners = { li["Owner's Names"]:li['Pets Name'] for li in dic2 }
    result = {}
    for owner, pet in owners.items():
        if owner in result :
            result[owner].append(ages[pet])
        else:
            result[owner] = [ages[pet]]

然后您的结果是{'Eva': [4, 8, 2]}类型的词典,但您可以使用列表推导将其恢复为dict列表(如果需要)

    result = [ {k:v} for k,v in result ]

答案 3 :(得分:1)

只是较短版本的Backtracks回复(工作正常,但我更喜欢更短,更实用)。

owners = {name: [] for name in list(set(map(lambda r: r["Owner's Names"], dic2)))}

for pet in dic1:
    for owner_mapping in dic2:
        if owner_mapping["Pets Names"] == pet["Pets Name"]:
            owners[ owner_mapping["Owner's Names"] ].append(pet["Age"])

编辑以演示迭代结果集(owners):

for owners_name, pets_ages_list in owners.items():
    print owners_name
    print pets_ages_list
    for pet_age in pets_ages_list:
        print pet_age