How do I convert a dictionary to a flat list?
Since you are using Python 2.7, I would recommend using dict.iteritems
or dict.viewitems
and make a list like
>>> [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
better than dict.items
, because they do not create a list of key-value pairs.
If you're wondering how you can write portable code that is efficient in Python 3.x as well, then you're just repeating keys like this.
>>> [item for k in d for item in (k, d[k])]
['a', 1, 'c', 3, 'b', 2]
source to share
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 the keys is not always the order in which they are stored. If you want to keep the order you can find ordereddict
source to share