treecoder
treecoder

Reputation: 45141

Handling tuples as values within a dictionary (in list comprehensions)

I have a dictionary like this:

>>> pprint.pprint(d)
{'a': ('abc', 'pqr', 'xyz'),
 'b': ('abc', 'lmn', 'uvw'),
 'c': ('efg', 'xxx', 'yyy')}

Now, given a variable x, I want to be able to list all the keys from the dict where the first element in the tuple is equal to x. Hence I do this (on Python 2.6):

>>> [ k for k, v in d if v[0] == x ]

And I get

Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 1 value to unpack

How can I correct this?

Upvotes: 2

Views: 85

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 77013

You're almost there, just forgot the .items() with the dict:

>>> d = {'a': ('abc', 'pqr', 'xyz'),
...  'b': ('abc', 'lmn', 'uvw'),
...  'c': ('efg', 'xxx', 'yyy')}
>>> x = 'abc'
>>> [ k for k, v in d.items() if v[0] == x ]
['a', 'b']

If you don't want to use .items, you could iterate on the key itself as well:

>>> [ k for k in d if d[k][0] == x ]
['a', 'b']

Upvotes: 5

Related Questions