Tuple list from dict in Python

PythonListDictionaryKey Value

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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())

Solution 2 - Python

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

Solution 3 - Python

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).

Solution 4 - Python

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, https://stackoverflow.com/questions/1679384/converting-python-dictionary-to-list.

Solution 5 - Python

For Python > 2.5:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManuel AraozView Question on Stackoverflow
Solution 1 - PythonAndrew KeetonView Answer on Stackoverflow
Solution 2 - PythonKenan BanksView Answer on Stackoverflow
Solution 3 - PythonAlex MartelliView Answer on Stackoverflow
Solution 4 - PythonLeonardoView Answer on Stackoverflow
Solution 5 - PythonKroliqueView Answer on Stackoverflow