Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a dictionary into a flat list?

Given a Python dict like:

{
  'a': 1,
  'b': 2,
  'c': 3
}

What's an easy way to create a flat list with keys and values in-line? E.g.:

['a', 1, 'b', 2, 'c', 3]
like image 456
blah238 Avatar asked Dec 23 '14 00:12

blah238


2 Answers

Since you are using Python 2.7, I would recommend using dict.iteritems or dict.viewitems and list comprehension, like this

>>> [item for pair in d.iteritems() for item in pair]
['a', 1, 'c', 3, 'b', 2]
>>> [item for pair in d.viewitems() for item in pair]
['a', 1, 'c', 3, 'b', 2]

dict.iteritems or dict.viewitems is better than dict.items because, they don't create a list of key-value pairs.

If you are wondering how you can write portable code which would be efficient in Python 3.x as well, then you just iterate the keys like this

>>> [item for k in d for item in (k, d[k])]
['a', 1, 'c', 3, 'b', 2]
like image 169
thefourtheye Avatar answered Nov 15 '22 05:11

thefourtheye


In [39]: d = {                                   
  'a': 1,
  'b': 2,
  'c': 3
}

In [40]: list(itertools.chain.from_iterable(d.items()))
Out[40]: ['b', 2, 'a', 1, 'c', 3]

Note that dicts are unordered, which means that the order in which you enter keys is not always the order in which they are stored. If you want to preserve order, you might be looking for an ordereddict

like image 26
inspectorG4dget Avatar answered Nov 15 '22 04:11

inspectorG4dget