How can I convert a dictionary to a tuple in python?
python
Solution
You can use `itertools.chain`. Note that this tuple will not have reproducible order, because dictionaries don't have one:
In [1]: d = {'1': 'stack', '2': 'over', '3': 'flow'}
In [2]: from itertools import chain
In [3]: tuple(chain.from_iterable(d.items()))
Out[3]: ('1', 'stack', '3', 'flow', '2', 'over')
In Python 2.x, you can use `d.iteritems()` instead of `d.items()`.
Edit: As EdChum notes in the comment, you can ensure the order by applying `sorted` to the items. Note, however, that by default strings are sorted in lexicographical order:
In [4]: sorted(['2', '10'])
Out[4]: ['10', '2']
You can override this by providing the `key` parameter to `sorted`:
In [5]: key = lambda i: (int(i[0]), i[1])
In [6]: tuple(chain.from_iterable(sorted(d.items(), key=key)))
Out[6]: ('1', 'stack', '2', 'over', '3', 'flow')
Problem
You may saw this kind of questions a lot, but my demand here is different. Say I have a dictionary `d = {'1': 'stack', '2': 'over', '3': 'flow'}`, and I want to make a tuple like `t = ('1', 'stack', '2', 'over', '3', 'flow')` What's the simplest way to do it?