52

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Manuel Araoz
  • 15,962
  • 24
  • 71
  • 95

5 Answers5

91

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())
Community
  • 1
  • 1
Andrew Keeton
  • 22,195
  • 6
  • 45
  • 72
9

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
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
6

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.

Community
  • 1
  • 1
Leonardo
  • 94
  • 1
  • 7
6

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

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Meh, I'm not sure I like that... thanks for the tip, though. – Andrew Keeton Aug 18 '09 at 19:52
  • @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. – Kenan Banks Aug 18 '09 at 19:57
  • @Triptych I was just grumbling that they chose to make the iterator the default view. – Andrew Keeton Aug 18 '09 at 19:59
  • 3
    Andrew, I think that choice just reflects the fact that the iterator is what you want most of the time. – Ben Hoyt Aug 18 '09 at 22:18
  • 2
    @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!-) – Alex Martelli Aug 19 '09 at 01:29
-2

For Python > 2.5:

a = {'1' : 10, '2' : 20 }
list(a.itervalues())
Krolique
  • 682
  • 9
  • 14