Tuple list from dict in Python

75,932

Solution 1

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

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

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

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.

Share:
75,932
Manuel Araoz
Author by

Manuel Araoz

I'm just trying to learn a bit of programming.

Updated on July 09, 2022

Comments

  • Manuel Araoz
    Manuel Araoz almost 2 years

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

  • Andrew Keeton
    Andrew Keeton over 14 years
    Meh, I'm not sure I like that... thanks for the tip, though.
  • Kenan Banks
    Kenan Banks over 14 years
    @Andrew - he's basically that in Python 3+, the behavior of dict.items(), will be changing to match the behavior of dict.iteritems(), as I described them in my post.
  • Andrew Keeton
    Andrew Keeton over 14 years
    @Triptych I was just grumbling that they chose to make the iterator the default view.
  • Jim
    Jim over 14 years
    the for loop could be used to make a list comprehension or a generator.
  • Ben Hoyt
    Ben Hoyt over 14 years
    Andrew, I think that choice just reflects the fact that the iterator is what you want most of the time.
  • Alex Martelli
    Alex Martelli over 14 years
    @Andrew, benhoyt is right -- the vast majority of uses are just looping, and making a list explicitly in the rare cases where you do need a list is a very Pythonic approach after all!-)
  • Anentropic
    Anentropic over 12 years
    that's a flat list of values, not the list of (key, value) tuples the poster was asking for