2

I am trying to get a list of tuple pairs from a dictionary that has a list as value.

d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
print(d.items())
>>[('a', [1, 2]), ('b', [4, 5]),('c', [7, 8]) ]

how do I get the list in this form

[('a', 1),('a', 2), ('b',4),('b',5),('c',7),('c',8)]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • 1
    Possible duplicate of [How can I convert a Python dictionary to a list of tuples?](http://stackoverflow.com/questions/674519/how-can-i-convert-a-python-dictionary-to-a-list-of-tuples) – l'L'l Mar 07 '16 at 04:06
  • This is a little different than that. This is not just turning key:value into a list of tuples. – Goodies Mar 07 '16 at 04:08

3 Answers3

2

Using a simple list comprehension:

d = {'a': [1,2,3], 'b': [4,5,6]}
l = [(k, v) for k in d for v in d[k]]
print(l)  # => [('a', 1), ('a', 2), ('a', 3), ('b', 4), ('b', 5), ('b', 6)]

There's likely other ways to do it, but this is simplistic and doesn't require other libraries.

Goodies
  • 4,439
  • 3
  • 31
  • 57
2

Its Simple, use one-liner :)

>>>
>>> d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
>>> [(key,item) for item in value for  key, value in d.iteritems()]
[('a', 4), ('c', 4), ('b', 4), ('a', 5), ('c', 5), ('b', 5)]
>>>

if you want to sort use built in funciton

>>> d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
>>> sorted([(key,item) for item in value for  key, value in d.iteritems()])
[('a', 4), ('a', 5), ('b', 4), ('b', 5), ('c', 4), ('c', 5)]
>>>
Nazmul Hasan
  • 6,840
  • 13
  • 36
  • 37
1
>>> d = {'a': [1, 2], 'b': [4, 5], 'c': [7, 8]}

You can access the key, value pairs using dict.items().

>>> list(d.items())
[('a', [1, 2]), ('c', [7, 8]), ('b', [4, 5])]

Then you can iterate over the pairs and iterate over the list values:

>>> [(key, value) for (key, values) in d.items()
...  for value in values]
[('a', 1), ('a', 2), ('c', 7), ('c', 8), ('b', 4), ('b', 5)]

The dictionary keys are not ordered alphabetically. If you want the exact output in your question you need to sort them, either before creating your list or after:

>>> pairs = _
>>> sorted(pairs)
[('a', 1), ('a', 2), ('b', 4), ('b', 5), ('c', 7), ('c', 8)]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99