-7

Given a dictionary

{
   'a': [1, 2, 3],
   'b': [4, 5, 6]
}

how do I get the output

[
   ['a', 1, 2, 3],
   ['b', 4, 5, 6]
]
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
Boris Lai
  • 1
  • 2

3 Answers3

4

Do you mean:

>>> a = {
...    'a':[1,2,3],
...    'b':[4,5,6]
... }

>>> [[key]+value for key, value in a.items()]
[['b', 4, 5, 6], ['a', 1, 2, 3]]

If you need sorted:

>>> sorted([[key]+value for key, value in a.items()])
[['a', 1, 2, 3], ['b', 4, 5, 6]]
>>> 
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
0

This solution should be closer to what you want (key and values in one list per dictionary item):

d = {
   'a':[1,2,3],
   'b':[4,5,6]
}

print sorted([[key] + values for key, values in d.iteritems()])

Output:

[['a', 1, 2, 3], ['b', 4, 5, 6]]
Falko
  • 17,076
  • 13
  • 60
  • 105
  • dict object has no attribute 'iteritems'. – DavidK Dec 03 '15 at 08:46
  • @DavidK: [Yes it has](https://docs.python.org/2/library/stdtypes.html#dict.iteritems) (I guess since Python 2.2). But you can use `items()` as well. – Falko Dec 03 '15 at 08:48
  • seems Python 3 does not. – DavidK Dec 03 '15 at 08:49
  • @DavidK: Yep, on Python 3 `items()` return a **generator** like `iteritems()` on Python 2 does. So `iteritems()` has been instead with `items()` since Python 3. Like `range()` and `xrange()`. – Remi Guan Dec 03 '15 at 08:50
  • Ok, I found ["In python 3, items returns a view, which is pretty much the same as an iterator."](http://stackoverflow.com/a/13998541/3419103) – Falko Dec 03 '15 at 08:50
0

You need to use OrderedDict if you want to get a specific order.

If you want to sort according to the keys :

D = {'a':[1,2,3],'b':[4,5,6]}

[[k] + D[k] for k in sorted(D.keys())]
DavidK
  • 2,495
  • 3
  • 23
  • 38