Stagg
Stagg

Reputation: 309

Merge to different dictionaries

I have two lists of dictionaries like this:

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

I need to make a third list of dictionaries, being the keys (of the dictionaries) the owner's names, and the values the age of their respective pets. For example, given the two lists above, the output should be:

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

The main goal is to get the average of the each owner's pets ages but I think I can do it myself after I have the desired dict. So far I only have this:

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]

This gives me the lists of the name of the pets, their age, and the name of the owner's, but I don't know if it's relevant for the final function.

Thanks in advance.

Upvotes: 2

Views: 82

Answers (4)

smassey
smassey

Reputation: 5931

Just a shorter version of Backtracks reply (which works fine, but I prefer shorter and functional when ever possible).

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"])

EDIT to demonstrate iterating over the result set (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

Upvotes: 1

Diane M
Diane M

Reputation: 1512

Using some shortcuts :

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

Then your result is a dictionnary of type {'Eva': [4, 8, 2]} but you can use a list comprehension to get it back to a list of dict if needed

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

Upvotes: 2

Serge Ballesta
Serge Ballesta

Reputation: 149075

You can use simply comprehensions:

{ 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)) }

Upvotes: 2

backtrack
backtrack

Reputation: 8144

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

Upvotes: 3

Related Questions