Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a dictionary to a tuple in python?

Tags:

python

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?

like image 270
fish748 Avatar asked Dec 20 '25 23:12

fish748


1 Answers

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')
like image 137
Lev Levitsky Avatar answered Dec 23 '25 13:12

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!