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]
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With