Skip to content
Advertisement

How can I convert a dictionary into a list of tuples?

If I have a dictionary like:

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

How can I convert it to this?

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

And how can I convert it to this?

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

Advertisement

Answer

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]

For Python 3.6 and later, the order of the list is what you would expect.

In Python 2, you don’t need list.

Advertisement