How to compare two list of dictionaries for the key exist in one and not in another
Question:
-
I have 2 list of dictionary
-
parent list pa = [{'key1': '1A', 'key2': 2},{'key1': '1B', 'key3': 2},{'key1': '1C', 'key4': 2}]
-
child list ch = [{'key1': '1A', 'keyvalue2': 2},{'key1': '1B', 'keyvalue23': 2},{'key1': '1D', 'key4': 2}]
-
I need to get the key1
which is present in pa
and not in ch
Code is below
for each in pa:
for each_1 in ch:
if each['key1'] not in each_1['key1']:
print(each['key1'])
My out is
1A
1A
1B
1B
1C
1C
1C
My expected out is 1C
which present in pa
and not in ch
I have created two list and compare which is working. but it’s not the case like code below. I don’t want to create a extra space
pa_list = []
for each in pa:
if each['key1'] not in pa_list:
pa_list.append(each['key1'])
ch_list = []
for each in ch:
if each['key1'] not in ch_list:
ch_list.append(each['key1'])
[i for i in pa_list if i not in ch_list]
Answers:
Starting from your original code, I suggest you to use the for/else loop, not very well-known, but quite useful in your case:
pa = [{'key1': '1A', 'key2': 2},{'key1': '1B', 'key3': 2},{'key1': '1C', 'key4': 2}]
ch = [{'key1': '1A', 'keyvalue2': 2},{'key1': '1B', 'keyvalue23': 2},{'key1': '1D', 'key4': 2}]
for i in pa:
for j in ch:
if (i['key1'] == j['key1']):
break
else:
print(i['key1'])
It outputs only ‘1C’ without intermediate variable, as expected.
-
I have 2 list of dictionary
-
parent list
pa = [{'key1': '1A', 'key2': 2},{'key1': '1B', 'key3': 2},{'key1': '1C', 'key4': 2}]
-
child list
ch = [{'key1': '1A', 'keyvalue2': 2},{'key1': '1B', 'keyvalue23': 2},{'key1': '1D', 'key4': 2}]
-
I need to get the
key1
which is present inpa
and not inch
Code is below
for each in pa:
for each_1 in ch:
if each['key1'] not in each_1['key1']:
print(each['key1'])
My out is
1A
1A
1B
1B
1C
1C
1C
My expected out is 1C
which present in pa
and not in ch
I have created two list and compare which is working. but it’s not the case like code below. I don’t want to create a extra space
pa_list = []
for each in pa:
if each['key1'] not in pa_list:
pa_list.append(each['key1'])
ch_list = []
for each in ch:
if each['key1'] not in ch_list:
ch_list.append(each['key1'])
[i for i in pa_list if i not in ch_list]
Starting from your original code, I suggest you to use the for/else loop, not very well-known, but quite useful in your case:
pa = [{'key1': '1A', 'key2': 2},{'key1': '1B', 'key3': 2},{'key1': '1C', 'key4': 2}]
ch = [{'key1': '1A', 'keyvalue2': 2},{'key1': '1B', 'keyvalue23': 2},{'key1': '1D', 'key4': 2}]
for i in pa:
for j in ch:
if (i['key1'] == j['key1']):
break
else:
print(i['key1'])
It outputs only ‘1C’ without intermediate variable, as expected.