For example, the following code:
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
if any(x in string for x in dict):
print(dict[x])
Is there any way to get x? (or get dict[x] through another method?)
For example, the following code:
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
if any(x in string for x in dict):
print(dict[x])
Is there any way to get x? (or get dict[x] through another method?)
There are a few points that need to be rectified before the answer is provided :
any()
can be used only for iterable objects like a list, tuple or dictionary - hence the object that gets returned inside the condition you have defined wont be passed and would be unidentified for any()
List Comprehensions are an amazing way to manipulate values of an iterable and return your desired value in the form of a list, which can further be modified or printed as per your desire
Moving on to the original solution:
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
list_final = [x for x in dict if x in string]
A good approach is to get the output in the form of a list element (in case of more than one element:
print(list_final)
If you want it as a single element value (as a string) - very few cases, such as the one here:
print(list_final[0])
Just put "x in string" inside brackets.
So you would get
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
if any((x in string) for x in dict):
print(dict[x])
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
print([dict[x] for x in string.split() if x in dict])
# Output:
# ['a']
It is not clear what you are trying to achieve. The solution you are searching for could be:
res = [x for x in dict if x in string]
or
[print(x) for x in dict if x in string]
but the last one it is not the good way to use list comprehension.
p.s. you should not use dict as name for a dictionary
Assuming you want to get all values where their keys are inside your string, you can do the following:
mydict = {
"foo": "a",
"bar": "b",
"see": "c",
}
string = "foo in the city"
matches = [x for x in mydict if x in string]
for match in matches:
print(mydict[match])
According to your need. I think this is what you want.
dict = {
"foo": "a",
"bar": "b",
"see": "c",
}
s = "foo in the city"
result = [dict[x] for x in s.split() if dict.get(x,0) != 0]
print(result)
If you want to just print
[print(dict[x]) for x in s.split() if dict.get(x,0) != 0]
Output:
a
I think you want to check if any of the words in string
(please do not name variables as their type) is in the dict? If so, maybe this helps:
# make it a list
words = string.split(' ')
x = 'foo'
if any(x in words for x in dict):
print(dict[x])
# output:
# a