1

My question may be a bit weird, but I don't know how else to put it. The situation is that I've got a dict with tuples as keys:

{(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'}

I now want to get a list (or tuple) of all the values in the tuples in the dict. So the result should look like this:

[1, 2, 3, 4, 5, 6]

Does anybody know how I can do this in an efficient and pythonic way?

All tips are welcome!

[EDIT] Seeing that I get a lot of responses with some extra questions:

I don't care about the order, but possible duplicates should be removed..

kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

6

Chain the keys together, with a list comprehension for example:

[v for key in yourdict for v in key]

If you only need to iterate, using itertools.chain.from_iterable() could do:

from itertools import chain

for v in chain.from_iterable(yourdict):

A dictionary has no ordering, so the values from the keys won't be in any specific order either (although the 2 values per key do remain consecutive). You can always sort them with:

sorted(v for key in yourdict for v in key)

or

sorted(chain.from_iterable(yourdict))

If you don't care about order but don't want duplicates, then produce a set instead:

{v for key in yourdict for v in key}

Demo:

>>> yourdict = {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'}
>>> [v for key in yourdict for v in key]
[1, 2, 5, 6, 3, 4]
>>> from itertools import chain
>>> list(chain.from_iterable(yourdict))
[1, 2, 5, 6, 3, 4]
>>> sorted(v for key in yourdict for v in key)
[1, 2, 3, 4, 5, 6]
>>> sorted(chain.from_iterable(yourdict))
[1, 2, 3, 4, 5, 6]

And producing a set:

>>> anotherdict = {(1, 2): 'a', (3, 4): 'b', (4, 2): 'c'}
>>> {v for key in yourdict for v in key}
set([1, 2, 3, 4, 5, 6])
>>> {v for key in anotherdict for v in key}
set([1, 2, 3, 4])
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Since you mentioned order doesn't matter

d = {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'}
set().union(*d.viewkeys())
set([1, 2, 3, 4, 5, 6])
iruvar
  • 22,736
  • 7
  • 53
  • 82