mike mike - 1 year ago 107
Python Question

How can I convert a Python dictionary to 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') ]

Answer Source
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessary.

See: items(), iteritems()

In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download