Reputation: 27
The problem is the following, for instance:
lst = ['2456', '1871', '187']
d = {
'1871': '1',
'2456': '0',
}
for i in lst:
if any(i in x for x in d.keys()):
print i
% python test.py
2456
1871
187
So, I need to get all the elements from the list "lst" that are contained in the keys of dictionary "d", without a substring match, cause if I do "print d[i]", I get an error.
Upvotes: 0
Views: 115
Reputation: 195059
this line should do the job:
l=[e for e in d if e in lst]
with your data:
In [5]: l=[e for e in d if e in lst]
In [6]: l
Out[7]: ['2456', '1871']
Upvotes: 1
Reputation: 19416
>>> for i in li:
if i in d:
print "{0} => {1}".format(i,d[i])
2456 => 0
1871 => 1
In a list comprehension:
>>> [i for i in li if i in d]
['2456', '1871']
Upvotes: 0
Reputation: 6828
Using sets
:
lst = ['2456', '1871', '187']
d = {'1871': '1', '2456': '0'}
print(set(lst) & set(d.keys())) # prints '{'2456', '1871'}'
Upvotes: 0
Reputation: 133554
>>> lst = ['2456', '1871', '187']
>>> d = {
'1871': '1',
'2456': '0',
}
>>> [x for x in lst if x in d]
['2456', '1871']
Upvotes: 3