'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]


Solution 1:[1]

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

Solution 2:[2]

You can use sum:

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

Solution 3:[3]

res_list = []
for k, v in d:
    res_list.append(k).append(v)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 inspectorG4dget
Solution 2
Solution 3 Baohe Chen