Tuple list from dict in Python

Question:

How can I obtain a list of key-value tuples from a dict in Python?

Asked By: Manuel Araoz

||

Answers:

For Python 2.x only (thanks Alex):

yourdict = {}
# ...
items = yourdict.items()

See http://docs.python.org/library/stdtypes.html#dict.items for details.

For Python 3.x only (taken from Alex’s answer):

yourdict = {}
# ...
items = list(yourdict.items())
Answered By: Andrew Keeton

For a list of of tuples:

my_dict.items()

If all you’re doing is iterating over the items, however, it is often preferable to use dict.iteritems(), which is more memory efficient because it returns only one item at a time, rather than all items at once:

for key,value in my_dict.iteritems():
     #do stuff
Answered By: Kenan Banks

In Python 2.*, thedict.items(), as in @Andrew’s answer. In Python 3.*, list(thedict.items()) (since there items is just an iterable view, not a list, you need to call list on it explicitly if you need exactly a list).

Answered By: Alex Martelli

For Python > 2.5:

a = {'1' : 10, '2' : 20 }
list(a.itervalues())
Answered By: Krolique

Converting from dict to list is made easy in Python. Three examples:

d = {'a': 'Arthur', 'b': 'Belling'}

d.items() [('a', 'Arthur'), ('b', 'Belling')]

d.keys() ['a', 'b']

d.values() ['Arthur', 'Belling']

as seen in a previous answer, Converting Python Dictionary to List.

Answered By: Leonardo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.