Wednesday, August 19, 2009

Python: How to convert a dictionary into a list of key-value

Using the list() function, we can convert a dictionary into a list of key-value tuple.
>>> x = {'a':1, 'b':2}
>>> x
{'a': 1, 'b': 2}
>>> y = list(x.items())
>>> y
[('a', 1), ('b', 2)
To convert back into dictionary, use the dict() function.
>>> z = dict(y)
>>> z
{'a': 1, 'b': 2}