[Python] How to show difference between two list of dictionaries

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I have these two lists:

    list1 = [
    {'name': 'one', 'email': 'one@gmail.com', 'phone': '111'},
    {'name': 'two', 'email': 'two@gmail.com', 'phone': '111'},
    {'name': 'three', 'email': 'three@gmail.com', 'phone': '333'},
    {'name': 'four', 'email': 'four@gmail.com', 'phone': '444'},
    ]
    list2 = [
    {'first_name': 'three', 'email': 'three@gmail.com', 'phone_number': '333'},
    {'first_name': 'four', 'email': 'four@gmail.com', 'phone_number': '444'},
    {'first_name': 'five', 'email': 'five@gmail.com', 'phone_number': '555'},
    ]


    I know how to find difference between two lists based on a key:

    list1_only = list(set([x['phone'] for x in list1]) - set([x['phone_number'] for x in list2]))


    But the current output is:

    ['111']


    But I'm going to have this output finally:

    [
    {'name': 'one', 'email': 'one@gmail.com', 'phone': '111'},
    {'name': 'two', 'email': 'two@gmail.com', 'phone': '111'}
    ]


    I know this way, but I think (and am sure) there's a better way for it:

    for l in list1:
    for d in diff:
    if d == l['phone']:
    print(l)



    I read other questions like this, but it prints the whole list (not the difference values):

    [x for x in list2 if x['phone_number'] not in list1]


    Would you please help me regarding this?

    Are there any one-line ways to replace with list1_only = list(set([x['phone'] for x in list1]) - set([x['phone_number'] for x in list2]))?

    Continue reading...

Compartilhe esta Página