How do I convert a dictionary to a flat list?

Given Python dict

as:

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

      

What's an easy way to create a flat list with keys and values ​​in a string? For example:.

['a', 1, 'b', 2, 'c', 3]

      

+3


source to share


3 answers


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]

      

+4


source


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

+4


source


You can use sum

:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> sum(d.items(), tuple())
('a', 1, 'c', 3, 'b', 2)

      

+1


source







All Articles