Reputation: 43169
Imagine I have the following list
lst = [("key1", "2"), ("key3", "4"), "somestring", 12345]
And I'd like to build a dict out of it (using a dictcomp, that is):
d = {key: value
for item in lst
for key, value in [item]
if isinstance(item, tuple)}
This will blow up with a ValueError
(too many values to unpack).
When is the if
clause being evaluated (which is crucial for the unpacking, of course) ?
Note: I know I could use a filter/lambda
before but wanted to know if it's possible in one step.
Upvotes: 1
Views: 94
Reputation: 17824
You can also use the following dictcomp:
{i[0]: i[1] for i in lst if isinstance(i, tuple)}
# {'key1': '2', 'key3': '4'}
Upvotes: 1
Reputation: 104
I think that is what you are looking for :
>>> lst = [("key1", "2"), ("key3", "4"), "somestring", 12345]
>>> dict([i for i in lst if type(i) is tuple])
{'key1': '2', 'key3': '4'}
Upvotes: 4