Simple/quick to code: loop in the list of dictionaries, stop when you find it.
But complexity isn't good if you perform several searches. Instead, create a dictionary of your dictionaries.
- The keys are the union of keys
- The values are lists of couples (value, origin dict)
like this:
companies = {'google': 'value_1', 'facebook': 'value_2'}
names = {'alex': 'value_3', 'john': 'value_4'}
import collections
c = collections.defaultdict(list)
for d in [companies,names]:
for k,v in d.items():
c[k].append((v,d))
now:
print(c.get('google'))
prints:
[('value_1', {'google': 'value_1', 'facebook': 'value_2'})
Now if I add a common key in both dicts:
names = {'alex': 'value_3', 'john': 'value_4', 'facebook':'value_5'}
print(c.get('facebook'))
we get a list of all values and the origin dictionaries:
[('value_2', {'google': 'value_1', 'facebook': 'value_2'}),
('value_5', {'alex': 'value_3', 'john': 'value_4', 'facebook': 'value_5'})]
With that solution, even if you have a lot of dictionaries, the lookup is always O(1)
once the new big dictionary is built. The build is amortized after 2 or 3 lookups.
Above, we see that the origin dictionary has been retained. Now you can choose how you identify this dictionary. I chose to put the reference itself as I had no constraint.