Getting the difference between 2 lists that contain dictionaries [duplicate]











up vote
12
down vote

favorite
2













This question already has an answer here:




  • Finding difference between two list of dictionary in Python

    3 answers



  • Get difference between two lists

    25 answers




list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]


Is there a way to get the difference between those two lists?



Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}










share|improve this question















marked as duplicate by Maurice Meyer, Jörg W Mittag, jpp python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 11 at 12:56


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 4




    ^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
    – LeKhan9
    Nov 11 at 0:58










  • Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
    – Alex Hall
    Nov 11 at 9:40










  • "Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
    – Jörg W Mittag
    Nov 11 at 9:54















up vote
12
down vote

favorite
2













This question already has an answer here:




  • Finding difference between two list of dictionary in Python

    3 answers



  • Get difference between two lists

    25 answers




list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]


Is there a way to get the difference between those two lists?



Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}










share|improve this question















marked as duplicate by Maurice Meyer, Jörg W Mittag, jpp python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 11 at 12:56


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 4




    ^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
    – LeKhan9
    Nov 11 at 0:58










  • Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
    – Alex Hall
    Nov 11 at 9:40










  • "Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
    – Jörg W Mittag
    Nov 11 at 9:54













up vote
12
down vote

favorite
2









up vote
12
down vote

favorite
2






2






This question already has an answer here:




  • Finding difference between two list of dictionary in Python

    3 answers



  • Get difference between two lists

    25 answers




list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]


Is there a way to get the difference between those two lists?



Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}










share|improve this question
















This question already has an answer here:




  • Finding difference between two list of dictionary in Python

    3 answers



  • Get difference between two lists

    25 answers




list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]


Is there a way to get the difference between those two lists?



Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}





This question already has an answer here:




  • Finding difference between two list of dictionary in Python

    3 answers



  • Get difference between two lists

    25 answers








python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 10:12









Muntasir

6041818




6041818










asked Nov 11 at 0:51









narhz

664




664




marked as duplicate by Maurice Meyer, Jörg W Mittag, jpp python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 11 at 12:56


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Maurice Meyer, Jörg W Mittag, jpp python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 11 at 12:56


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 4




    ^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
    – LeKhan9
    Nov 11 at 0:58










  • Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
    – Alex Hall
    Nov 11 at 9:40










  • "Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
    – Jörg W Mittag
    Nov 11 at 9:54














  • 4




    ^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
    – LeKhan9
    Nov 11 at 0:58










  • Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
    – Alex Hall
    Nov 11 at 9:40










  • "Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
    – Jörg W Mittag
    Nov 11 at 9:54








4




4




^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
– LeKhan9
Nov 11 at 0:58




^ not necessarily a duplicate since the elements here are dictionaries which are not readily hashable using a set
– LeKhan9
Nov 11 at 0:58












Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
– Alex Hall
Nov 11 at 9:40




Do you really only have dictionaries with one key/value, or is that just for demonstration? Because it would probably make a lot more sense to just have one dictionary {key1: item1, key2: item2, ...} rather than a list.
– Alex Hall
Nov 11 at 9:40












"Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
– Jörg W Mittag
Nov 11 at 9:54




"Is there a way to get the difference between those two lists?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and then and only then narrow your problem down to a concise, focused, simple, short, reproducible Minimal, Complete, and Verifiable example and ask a specific, focused, narrow question on Stack Overflow.
– Jörg W Mittag
Nov 11 at 9:54












6 Answers
6






active

oldest

votes

















up vote
12
down vote



accepted










You could use a list comprehension:



list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

print([x for x in list2 if x not in list1])


Which will give [{'key3': 'item3'}]






share|improve this answer




























    up vote
    2
    down vote













    You can use set() with a comprehension like this example:



    def get_diff(elm1, elm2):
    a = set((m, n) for k in elm1 for m, n in k.items())
    b = set((m, n) for k in elm2 for m, n in k.items())
    if len(b) > len(a):
    return dict(b - a)
    return dict(a - b)


    list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
    list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
    get_diff(list1, list2)


    Output:



    {'key3': 'item3'}





    share|improve this answer




























      up vote
      1
      down vote













      in_list1_not_in_list2 = [i for i in list1 if i not in list2]
      in_list2_not_in_list1 = [i for i in list2 if i not in list1]





      share|improve this answer




























        up vote
        0
        down vote













        Since dictionaries are not hashable there isn't an easy way to hash, but since we have one key and one val per dictionary, we can build our own key! So you can do something like this:



        list1_set = set()

        for dictionary in list1:
        key = dictionary.keys()[0]
        vals = dictionary.values()[0]
        custom_key = '{}|{}'.format(key,vals)
        list1_set.add(custom_key)

        differences =
        for dictionary in list2:
        key = dictionary.keys()[0]
        vals = dictionary.values()[0]
        custom_key = '{}|{}'.format(key,vals)

        if custom_key not in list1_set:
        differences.append(dictionary)

        print differences


        output:



        [{'key3': 'item3'}]


        Not this solution is much more scalable then simply iterating through the first list because of the constant lookup ability.






        share|improve this answer






























          up vote
          0
          down vote













          You can also try using set.symmetric_difference() to get the difference between the sets both ways:



          list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
          list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

          set1 = set(tuple(x.items())[0] for x in list1)
          set2 = set(tuple(x.items())[0] for x in list2)

          print([dict(list(set1.symmetric_difference(set2)))])
          # [{'key3': 'item3'}]

          print([dict(list(set2.symmetric_difference(set1)))])
          # [{'key3': 'item3'}]


          Another way would be to use itertools.filterfalse():



          from itertools import filterfalse

          diff1 = list(filterfalse(lambda d: d in list2, list1))
          diff2 = list(filterfalse(lambda d: d in list1, list2))

          print(diff1 + diff2)
          # [{'key3': 'item3'}]





          share|improve this answer






























            up vote
            0
            down vote













            You can inform the dictionary how to hash itself and then you could use sets



            import json

            class HashableDict(dict):
            def __hash__(self):
            # convert the dictionary to something hashable - in this case a str
            return hash(json.dumps(self))


            then you can do



            hashable_list1 = map(HashableDict, list1)
            hashable_list2 = map(HashableDict, list2)
            set(hashable_list2).difference(hashable_list1)


            difference gives you the elements in lists2 that are not in list1.



            If you wanted all the difference, so all the items that are not in both lists, do:



            set(hashable_list2).symmetric_difference(hashable_list1)


            Note this will not work for all dictionaries (e.g., dictionaries containing objects the json.dumps cannot work with) unless you handle those explicitly too with a custom JSONEncoder






            share|improve this answer






























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              12
              down vote



              accepted










              You could use a list comprehension:



              list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
              list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

              print([x for x in list2 if x not in list1])


              Which will give [{'key3': 'item3'}]






              share|improve this answer

























                up vote
                12
                down vote



                accepted










                You could use a list comprehension:



                list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                print([x for x in list2 if x not in list1])


                Which will give [{'key3': 'item3'}]






                share|improve this answer























                  up vote
                  12
                  down vote



                  accepted







                  up vote
                  12
                  down vote



                  accepted






                  You could use a list comprehension:



                  list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                  list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                  print([x for x in list2 if x not in list1])


                  Which will give [{'key3': 'item3'}]






                  share|improve this answer












                  You could use a list comprehension:



                  list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                  list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                  print([x for x in list2 if x not in list1])


                  Which will give [{'key3': 'item3'}]







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 11 at 0:56









                  Simon

                  4,14883070




                  4,14883070
























                      up vote
                      2
                      down vote













                      You can use set() with a comprehension like this example:



                      def get_diff(elm1, elm2):
                      a = set((m, n) for k in elm1 for m, n in k.items())
                      b = set((m, n) for k in elm2 for m, n in k.items())
                      if len(b) > len(a):
                      return dict(b - a)
                      return dict(a - b)


                      list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                      list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
                      get_diff(list1, list2)


                      Output:



                      {'key3': 'item3'}





                      share|improve this answer

























                        up vote
                        2
                        down vote













                        You can use set() with a comprehension like this example:



                        def get_diff(elm1, elm2):
                        a = set((m, n) for k in elm1 for m, n in k.items())
                        b = set((m, n) for k in elm2 for m, n in k.items())
                        if len(b) > len(a):
                        return dict(b - a)
                        return dict(a - b)


                        list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                        list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
                        get_diff(list1, list2)


                        Output:



                        {'key3': 'item3'}





                        share|improve this answer























                          up vote
                          2
                          down vote










                          up vote
                          2
                          down vote









                          You can use set() with a comprehension like this example:



                          def get_diff(elm1, elm2):
                          a = set((m, n) for k in elm1 for m, n in k.items())
                          b = set((m, n) for k in elm2 for m, n in k.items())
                          if len(b) > len(a):
                          return dict(b - a)
                          return dict(a - b)


                          list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                          list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
                          get_diff(list1, list2)


                          Output:



                          {'key3': 'item3'}





                          share|improve this answer












                          You can use set() with a comprehension like this example:



                          def get_diff(elm1, elm2):
                          a = set((m, n) for k in elm1 for m, n in k.items())
                          b = set((m, n) for k in elm2 for m, n in k.items())
                          if len(b) > len(a):
                          return dict(b - a)
                          return dict(a - b)


                          list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                          list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
                          get_diff(list1, list2)


                          Output:



                          {'key3': 'item3'}






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 11 at 1:13









                          Chiheb Nexus

                          4,60031527




                          4,60031527






















                              up vote
                              1
                              down vote













                              in_list1_not_in_list2 = [i for i in list1 if i not in list2]
                              in_list2_not_in_list1 = [i for i in list2 if i not in list1]





                              share|improve this answer

























                                up vote
                                1
                                down vote













                                in_list1_not_in_list2 = [i for i in list1 if i not in list2]
                                in_list2_not_in_list1 = [i for i in list2 if i not in list1]





                                share|improve this answer























                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  in_list1_not_in_list2 = [i for i in list1 if i not in list2]
                                  in_list2_not_in_list1 = [i for i in list2 if i not in list1]





                                  share|improve this answer












                                  in_list1_not_in_list2 = [i for i in list1 if i not in list2]
                                  in_list2_not_in_list1 = [i for i in list2 if i not in list1]






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 11 at 0:56









                                  qwerty asdf

                                  92




                                  92






















                                      up vote
                                      0
                                      down vote













                                      Since dictionaries are not hashable there isn't an easy way to hash, but since we have one key and one val per dictionary, we can build our own key! So you can do something like this:



                                      list1_set = set()

                                      for dictionary in list1:
                                      key = dictionary.keys()[0]
                                      vals = dictionary.values()[0]
                                      custom_key = '{}|{}'.format(key,vals)
                                      list1_set.add(custom_key)

                                      differences =
                                      for dictionary in list2:
                                      key = dictionary.keys()[0]
                                      vals = dictionary.values()[0]
                                      custom_key = '{}|{}'.format(key,vals)

                                      if custom_key not in list1_set:
                                      differences.append(dictionary)

                                      print differences


                                      output:



                                      [{'key3': 'item3'}]


                                      Not this solution is much more scalable then simply iterating through the first list because of the constant lookup ability.






                                      share|improve this answer



























                                        up vote
                                        0
                                        down vote













                                        Since dictionaries are not hashable there isn't an easy way to hash, but since we have one key and one val per dictionary, we can build our own key! So you can do something like this:



                                        list1_set = set()

                                        for dictionary in list1:
                                        key = dictionary.keys()[0]
                                        vals = dictionary.values()[0]
                                        custom_key = '{}|{}'.format(key,vals)
                                        list1_set.add(custom_key)

                                        differences =
                                        for dictionary in list2:
                                        key = dictionary.keys()[0]
                                        vals = dictionary.values()[0]
                                        custom_key = '{}|{}'.format(key,vals)

                                        if custom_key not in list1_set:
                                        differences.append(dictionary)

                                        print differences


                                        output:



                                        [{'key3': 'item3'}]


                                        Not this solution is much more scalable then simply iterating through the first list because of the constant lookup ability.






                                        share|improve this answer

























                                          up vote
                                          0
                                          down vote










                                          up vote
                                          0
                                          down vote









                                          Since dictionaries are not hashable there isn't an easy way to hash, but since we have one key and one val per dictionary, we can build our own key! So you can do something like this:



                                          list1_set = set()

                                          for dictionary in list1:
                                          key = dictionary.keys()[0]
                                          vals = dictionary.values()[0]
                                          custom_key = '{}|{}'.format(key,vals)
                                          list1_set.add(custom_key)

                                          differences =
                                          for dictionary in list2:
                                          key = dictionary.keys()[0]
                                          vals = dictionary.values()[0]
                                          custom_key = '{}|{}'.format(key,vals)

                                          if custom_key not in list1_set:
                                          differences.append(dictionary)

                                          print differences


                                          output:



                                          [{'key3': 'item3'}]


                                          Not this solution is much more scalable then simply iterating through the first list because of the constant lookup ability.






                                          share|improve this answer














                                          Since dictionaries are not hashable there isn't an easy way to hash, but since we have one key and one val per dictionary, we can build our own key! So you can do something like this:



                                          list1_set = set()

                                          for dictionary in list1:
                                          key = dictionary.keys()[0]
                                          vals = dictionary.values()[0]
                                          custom_key = '{}|{}'.format(key,vals)
                                          list1_set.add(custom_key)

                                          differences =
                                          for dictionary in list2:
                                          key = dictionary.keys()[0]
                                          vals = dictionary.values()[0]
                                          custom_key = '{}|{}'.format(key,vals)

                                          if custom_key not in list1_set:
                                          differences.append(dictionary)

                                          print differences


                                          output:



                                          [{'key3': 'item3'}]


                                          Not this solution is much more scalable then simply iterating through the first list because of the constant lookup ability.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 11 at 1:40

























                                          answered Nov 11 at 0:57









                                          LeKhan9

                                          921112




                                          921112






















                                              up vote
                                              0
                                              down vote













                                              You can also try using set.symmetric_difference() to get the difference between the sets both ways:



                                              list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                                              list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                                              set1 = set(tuple(x.items())[0] for x in list1)
                                              set2 = set(tuple(x.items())[0] for x in list2)

                                              print([dict(list(set1.symmetric_difference(set2)))])
                                              # [{'key3': 'item3'}]

                                              print([dict(list(set2.symmetric_difference(set1)))])
                                              # [{'key3': 'item3'}]


                                              Another way would be to use itertools.filterfalse():



                                              from itertools import filterfalse

                                              diff1 = list(filterfalse(lambda d: d in list2, list1))
                                              diff2 = list(filterfalse(lambda d: d in list1, list2))

                                              print(diff1 + diff2)
                                              # [{'key3': 'item3'}]





                                              share|improve this answer



























                                                up vote
                                                0
                                                down vote













                                                You can also try using set.symmetric_difference() to get the difference between the sets both ways:



                                                list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                                                list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                                                set1 = set(tuple(x.items())[0] for x in list1)
                                                set2 = set(tuple(x.items())[0] for x in list2)

                                                print([dict(list(set1.symmetric_difference(set2)))])
                                                # [{'key3': 'item3'}]

                                                print([dict(list(set2.symmetric_difference(set1)))])
                                                # [{'key3': 'item3'}]


                                                Another way would be to use itertools.filterfalse():



                                                from itertools import filterfalse

                                                diff1 = list(filterfalse(lambda d: d in list2, list1))
                                                diff2 = list(filterfalse(lambda d: d in list1, list2))

                                                print(diff1 + diff2)
                                                # [{'key3': 'item3'}]





                                                share|improve this answer

























                                                  up vote
                                                  0
                                                  down vote










                                                  up vote
                                                  0
                                                  down vote









                                                  You can also try using set.symmetric_difference() to get the difference between the sets both ways:



                                                  list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                                                  list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                                                  set1 = set(tuple(x.items())[0] for x in list1)
                                                  set2 = set(tuple(x.items())[0] for x in list2)

                                                  print([dict(list(set1.symmetric_difference(set2)))])
                                                  # [{'key3': 'item3'}]

                                                  print([dict(list(set2.symmetric_difference(set1)))])
                                                  # [{'key3': 'item3'}]


                                                  Another way would be to use itertools.filterfalse():



                                                  from itertools import filterfalse

                                                  diff1 = list(filterfalse(lambda d: d in list2, list1))
                                                  diff2 = list(filterfalse(lambda d: d in list1, list2))

                                                  print(diff1 + diff2)
                                                  # [{'key3': 'item3'}]





                                                  share|improve this answer














                                                  You can also try using set.symmetric_difference() to get the difference between the sets both ways:



                                                  list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
                                                  list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

                                                  set1 = set(tuple(x.items())[0] for x in list1)
                                                  set2 = set(tuple(x.items())[0] for x in list2)

                                                  print([dict(list(set1.symmetric_difference(set2)))])
                                                  # [{'key3': 'item3'}]

                                                  print([dict(list(set2.symmetric_difference(set1)))])
                                                  # [{'key3': 'item3'}]


                                                  Another way would be to use itertools.filterfalse():



                                                  from itertools import filterfalse

                                                  diff1 = list(filterfalse(lambda d: d in list2, list1))
                                                  diff2 = list(filterfalse(lambda d: d in list1, list2))

                                                  print(diff1 + diff2)
                                                  # [{'key3': 'item3'}]






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Nov 11 at 2:02

























                                                  answered Nov 11 at 1:52









                                                  RoadRunner

                                                  9,10831138




                                                  9,10831138






















                                                      up vote
                                                      0
                                                      down vote













                                                      You can inform the dictionary how to hash itself and then you could use sets



                                                      import json

                                                      class HashableDict(dict):
                                                      def __hash__(self):
                                                      # convert the dictionary to something hashable - in this case a str
                                                      return hash(json.dumps(self))


                                                      then you can do



                                                      hashable_list1 = map(HashableDict, list1)
                                                      hashable_list2 = map(HashableDict, list2)
                                                      set(hashable_list2).difference(hashable_list1)


                                                      difference gives you the elements in lists2 that are not in list1.



                                                      If you wanted all the difference, so all the items that are not in both lists, do:



                                                      set(hashable_list2).symmetric_difference(hashable_list1)


                                                      Note this will not work for all dictionaries (e.g., dictionaries containing objects the json.dumps cannot work with) unless you handle those explicitly too with a custom JSONEncoder






                                                      share|improve this answer



























                                                        up vote
                                                        0
                                                        down vote













                                                        You can inform the dictionary how to hash itself and then you could use sets



                                                        import json

                                                        class HashableDict(dict):
                                                        def __hash__(self):
                                                        # convert the dictionary to something hashable - in this case a str
                                                        return hash(json.dumps(self))


                                                        then you can do



                                                        hashable_list1 = map(HashableDict, list1)
                                                        hashable_list2 = map(HashableDict, list2)
                                                        set(hashable_list2).difference(hashable_list1)


                                                        difference gives you the elements in lists2 that are not in list1.



                                                        If you wanted all the difference, so all the items that are not in both lists, do:



                                                        set(hashable_list2).symmetric_difference(hashable_list1)


                                                        Note this will not work for all dictionaries (e.g., dictionaries containing objects the json.dumps cannot work with) unless you handle those explicitly too with a custom JSONEncoder






                                                        share|improve this answer

























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









                                                          You can inform the dictionary how to hash itself and then you could use sets



                                                          import json

                                                          class HashableDict(dict):
                                                          def __hash__(self):
                                                          # convert the dictionary to something hashable - in this case a str
                                                          return hash(json.dumps(self))


                                                          then you can do



                                                          hashable_list1 = map(HashableDict, list1)
                                                          hashable_list2 = map(HashableDict, list2)
                                                          set(hashable_list2).difference(hashable_list1)


                                                          difference gives you the elements in lists2 that are not in list1.



                                                          If you wanted all the difference, so all the items that are not in both lists, do:



                                                          set(hashable_list2).symmetric_difference(hashable_list1)


                                                          Note this will not work for all dictionaries (e.g., dictionaries containing objects the json.dumps cannot work with) unless you handle those explicitly too with a custom JSONEncoder






                                                          share|improve this answer














                                                          You can inform the dictionary how to hash itself and then you could use sets



                                                          import json

                                                          class HashableDict(dict):
                                                          def __hash__(self):
                                                          # convert the dictionary to something hashable - in this case a str
                                                          return hash(json.dumps(self))


                                                          then you can do



                                                          hashable_list1 = map(HashableDict, list1)
                                                          hashable_list2 = map(HashableDict, list2)
                                                          set(hashable_list2).difference(hashable_list1)


                                                          difference gives you the elements in lists2 that are not in list1.



                                                          If you wanted all the difference, so all the items that are not in both lists, do:



                                                          set(hashable_list2).symmetric_difference(hashable_list1)


                                                          Note this will not work for all dictionaries (e.g., dictionaries containing objects the json.dumps cannot work with) unless you handle those explicitly too with a custom JSONEncoder







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Nov 12 at 8:13

























                                                          answered Nov 11 at 1:22









                                                          rikAtee

                                                          4,65542956




                                                          4,65542956















                                                              Popular posts from this blog

                                                              Florida Star v. B. J. F.

                                                              Danny Elfman

                                                              Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues