Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if All Values Exist as Keys in Dictionary

Tags:

python

I have a list of values, and a dictionary. I want to ensure that each value in the list exists as a key in the dictionary. At the moment I'm using two sets to figure out if any values don't exist in the dictionary

unmapped = set(foo) - set(bar.keys())

Is there a more pythonic way to test this though? It feels like a bit of a hack?

like image 960
Batman Avatar asked Jun 06 '18 16:06

Batman


People also ask

How do you check if a key-value exists in a dictionary?

Check If Key Exists using the Inbuilt method keys() Using the Inbuilt method keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use if statement with 'in' operator to check if the key is present in the dictionary or not.

How do you check if a key exists in a dictionary Python?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

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 I know if a dictionary key has no value?

Method #2 : Using all() + values() In this, we can check for each key if all values are empty using all().


2 Answers

Your approach will work, however, there will be overhead from the conversion to set.

Another solution with the same time complexity would be:

all(i in bar for i in foo)

Both of these have time complexity O(len(foo))

bar = {str(i): i for i in range(100000)}
foo = [str(i) for i in range(1, 10000, 2)]

%timeit all(i in bar for i in foo)
462 µs ± 14.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit set(foo) - set(bar)
14.6 ms ± 174 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# The overhead is all the difference here:

foo = set(foo)
bar = set(bar)

%timeit foo - bar
213 µs ± 1.48 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The overhead here makes a pretty big difference, so I would choose all here.

like image 197
user3483203 Avatar answered Oct 17 '22 16:10

user3483203


Try this to see if there is any unmapped item:

has_unmapped = all( (x in bar) for x in foo   )

To see the unmapped items:

unmapped_items = [ x for x in foo if x not in bar ]
like image 1
Abhijith Asokan Avatar answered Oct 17 '22 16:10

Abhijith Asokan