How can I obtain a list of key-value tuples from a dict in python? Thanks
+13
A:
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())
Andrew Keeton
2009-08-18 19:42:48
Yep, the obvious way in Python 2.*.
Alex Martelli
2009-08-18 19:45:22
+3
A:
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
Triptych
2009-08-18 19:45:09
+2
A:
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
2009-08-18 19:45:45
@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.
Triptych
2009-08-18 19:57:10
@Triptych I was just grumbling that they chose to make the iterator the default view.
Andrew Keeton
2009-08-18 19:59:24
Andrew, I think that choice just reflects the fact that the iterator is what you want most of the time.
benhoyt
2009-08-18 22:18:27
@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
2009-08-19 01:29:26