mercredi 24 février 2021

Compare two dictionary lists, based on specific key

I'll try to be the more concise that I can.

Two dictionary lists as follows:

dictlist1 = [{name: john, age: 30}, {name: jessica, age: 56}, {name:kirk , age: 20}, {name: mario, age: 25}]

dictlist2 = [{name: john, job: engineer}, {name: jessica, job: nurse}, {name: mario, job: electrician}]

My objective is to match base on the key "name" on both dictionaries and, at the end, create a third dictionary list with the key that has no match, in this case {name:kirk , age: 20}, like this:

listfinal = [{name:kirk , age: 20}]

I've tried successfully compare the equal keys, creating a new dictionary with keys that matches and adding "job" key to it, doing this:

    for dict2 in dictlist2:
        for dict1 in dictlist1:
            if dict1['name'] == dict2['name']:
                matchname1 = dict2['name']
                dictoutput = {'name': matchname1, 'age': dict1['age'], 'group': dict2['group']}
                templist.append(dictoutput)

    for dictionay in templist:
        print(dictionay)

    Output:

    {'name': 'john', 'age': '30', 'job': 'engineer'}
    {'name': 'jessica', 'age': '56', 'job': 'nurse'} 
    {'name': 'mario', 'age': '25', 'job': 'electrician'}

But absolutely no luck to get kirk user alone, not even using "else" in the inner if statement or creating a new if statement and using not equal (!=). I always get all the users when printing.

Any orientation will be highly appreciated.

Aucun commentaire:

Enregistrer un commentaire