Jan
Jan

Reputation: 43169

Unpacking tuple values from mixed list

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

Answers (2)

Mykola Zotko
Mykola Zotko

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

T. Gwen
T. Gwen

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

Related Questions