0

I'm trying to compare 2 lists of dictionaries.

Please find an example below.

list1 = [
         {'code': '1111', 'description': 'Test'},
         {'code': '2222', 'description': 'Hello World'},
         {'code': '3333', 'description': 'Stack'},
         {'code': '4444', 'description': 'Gozilla'},
        ]

list2 = [
         {'code': '3333', 'description': 'Stack'},
         {'code': '4444', 'description': 'Megatron'},
         {'code': '5555', 'description': 'Winnie the Pooh'}
        ]

I am trying to :

  1. If ['code'] from list2 exist in list1, and if ['description'] is different, place it in a new list "updates".
  2. If ['code'] from list2 does not exist in list1, place it in a new list "new".

At the end the 2 new lists from my example should look like that :

updates = [
           {'code': '4444', 'description': 'Megatron'}
          ]

new =     [
           {'code': '5555', 'description': 'Winnie the Pooh'}
          ]

Any ideas how I could achieve that ?

Asocia
  • 5,935
  • 2
  • 21
  • 46
John
  • 89
  • 1
  • 8

2 Answers2

2

You can convert list1 to dict to make comparing codes easier:

list1 = [
         {'code': '1111', 'description': 'Test'},
         {'code': '2222', 'description': 'Hello World'},
         {'code': '3333', 'description': 'Stack'},
         {'code': '4444', 'description': 'Gozilla'},
        ]

list2 = [
         {'code': '3333', 'description': 'Stack'},
         {'code': '4444', 'description': 'Megatron'},
         {'code': '5555', 'description': 'Winnie the Pooh'}
        ]

updates = []
new = []

tmp = {d['code']: d['description'] for d in list1}
for d in list2:
    if d['code'] in tmp and d['description'] != tmp[d['code']]:
        updates.append(d)
    elif not d['code'] in tmp:
        new.append(d)

print(updates)
print(new)

Prints:

[{'code': '4444', 'description': 'Megatron'}]
[{'code': '5555', 'description': 'Winnie the Pooh'}]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0
#Otherwise,for example  4444 in between of list1 and list2

new_list = []
if list1[3].get('code')==list2[1].get('code'):
   new_list.append(list2[1])

print(new_list)
Setxh
  • 1