Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a given key is contained in any of multiple dictionaries

I have multiple dictionaries which contain data depending of their business value, e.g.:

companies = {'google': 'value_1', 'facebook': 'value_2'}
names = {'alex': 'value_3', 'john': 'value_4'}
...

I need to check whether a variable x is contained in any of these dictionaries, and to identify in which of these dictionaries it is contained. The number of such dictionaries can be huge, so checking them manually is not very effective. Is there something more pythonic than

if x in companies:
    pass    # do something
elif x in names:
    pass    # do something
...
like image 349
7duck Avatar asked Apr 02 '20 12:04

7duck


People also ask

How do you check if a key exists in a list of dictionaries?

The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.

How do you check if a Python dictionary contains a key?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().

How do you check if multiple keys are in a dictionary?

To check if multiple keys are in a dictionary:Use the dict. keys() method to get a view of the dictionary's keys. Check if the multiple keys are present in the view of the dictionary's keys.


1 Answers

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.

like image 63
Jean-François Fabre Avatar answered Oct 06 '22 00:10

Jean-François Fabre