'How to check efficiently two list of dictionary items in Python?
I have two lists:
l1 = [{"a":1, "b":2, "c":"pqr"}, {"a":3, "b":6, "c":"pir"}, {"a":2, "b":4, "c":""}]
l2 = [{"a":1, "b":3, "c":"def"}, {"a":2, "b":7, "c":"xyz"}]
I want to compare l1_item['a'] with l2_item['a']. If they match then I want to print l2_item['c']
I have used nested for loop to check each list of dictionary and then compare the value of l1_item['a'] with l2_item['a'].
I want to know if there is any other efficient way to check it without using nested for loop. I am having time complexity issue for larger data sets.
Solution 1:[1]
You could create a dictionary for the lookup where the value of the a-item is the key.
l1 = [{"a": 1, "b": 2, "c": "pqr"}, {"a": 3, "b": 6, "c": "pir"},
{"a": 2, "b": 4, "c": ""}]
l2 = [{"a": 1, "b": 3, "c": "def"}, {"a": 2, "b": 7, "c": "xyz"}]
lookup = {item['a']: item for item in l2}
for entry in l1:
item = lookup.get(entry['a'])
if item:
print(item['c'])
You need to create the dictionary once with O(n), but accessing it afterwards is O(1).
If the value of a could be in l2 more than once you will have to keep a list of items in the lookup dictionary.
from collections import defaultdict
l1 = [{"a": 1, "b": 2, "c": "pqr"}, {"a": 3, "b": 6, "c": "pir"},
{"a": 2, "b": 4, "c": ""}]
l2 = [{"a": 1, "b": 3, "c": "def"}, {"a": 2, "b": 7, "c": "xyz"}, {"a": 1, "b": 3, "c": "uvw"}, ]
lookup = defaultdict(list)
for item in l2:
lookup[item['a']].append(item)
for entry in l1:
items = lookup.get(entry['a'])
if items:
for item in items:
print(item['c'])
This will give you
def
uvw
xyz
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

