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?
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.
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.
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.
Method #2 : Using all() + values() In this, we can check for each key if all values are empty using all().
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With