0

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.

4 Answers 4

3
>>> lst = ['2456', '1871', '187']
>>> d = {
    '1871': '1',
    '2456': '0',
}
>>> [x for x in lst if x in d]
['2456', '1871']
Sign up to request clarification or add additional context in comments.

1 Comment

Yup nice quick look up and will preserve order and duplicate entries... +1 (although if that wasn't important I s'pose the next best set like approach would be d.viewkeys() & lst)
1

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']

Comments

0

Using sets:

lst = ['2456', '1871', '187']
d = {'1871': '1', '2456': '0'}

print(set(lst) & set(d.keys())) # prints '{'2456', '1871'}'

Comments

0
>>> 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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.