Assuming I've a dictionary,
mydict = { "short bread": "bread",
"black bread": "bread",
"banana cake": "cake",
"wheat bread": "bread" }
Given the string "wheat bread breakfast today"
I want to check if any key in my dictionary is contained in the string. If so, I want to return the value in the dictionary associated with that key.
I want to use a list comprehension for this.
Here's what I have so far.
mykeys = mydict.keys()
mystring = "wheat breads breakfast today"
if any(s in string for s in mykeys):
print("Yes")
This outputs Yes
as expected. What I really want to do is to use the s
variable to index into mydict. But s
has a limited scope inside the any() function. So the following does not work.
if any(s in mystring for s in mykeys):
print(mydict[s])
Any workaround? Many thanks!
Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.
Access Nested Dictionary Items This can be done using the special dictionary get() method. The get() method returns the value for the key if the key is in the dictionary, otherwise, it returns None. Hence, we never get the keyError if we use this method.
Python get() method can be used to check whether a particular key is present in the key-value pairs of the dictionary. The get() method actually returns the value associated with the key if the key happens to be present in the dictionary, else it returns 'None'.
Just loop through the keys and check each one.
for key in mydict:
if key in mystring:
print(mydict[key])
If you want to do it in a list comprehension, just check the key on each iteration.
[val for key,val in mydict.items() if key in mystring]
You could also filter the dictionary keys in the initial loop instead of a separate check.
for key in (key in mydict if key in mystring):
print(mydict[key])
Or you could use filter
if you feel like getting functional with it.
list(map(mydict.get, filter(lambda x:x in mystring, mydict)))
Or another way with filter (don't actually use this one, it's super unreadable and just here for fun).
list(filter(bool,[v*(k in mystring) for k,v in mydict.items()]))
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