there are 2 lists of dictionaries with the same keys, for example:
old = [{'key1': 'AAA', 'key2': 'value2', 'key3': 'value3'},{'key1': 'BBB', 'key2': 'value4', 'key3': 'value5'},{'key1': 'CCC', 'key2': 'value4', 'key3': 'value5'}]
new = [{'key1': 'BBB', 'key2': 'value2', 'key3': 'value3'},{'key1': 'CCC', 'key2': 'value4', 'key3': 'value1'}]
The task is to get old[0] ({'key1': AAA, ...}) via the key 'key1'.
Tried the method below, but if the length of the lists are different, it does not work:
for x in old:
for y in new:
if x['key1'] in y['key1']:
old.remove(x)
CodePudding user response:
Use the nested loop the other way round:
for y in new:
for x in old:
if x['key1'] == y['key1']:
old.remove(x)
print(old)
which produces:
[{'key1': 'AAA', 'key2': 'value2', 'key3': 'value3'}]