tags:

views:

3296

answers:

6

If I have a dictionary like:

{ 'a': 1, 'b': 2, 'c': 3 }

How can I convert it to this?

[ ('a', 1), ('b', 2), ('c', 3) ]

And how can I convert it to this?

[ (1, 'a'), (2, 'b'), (3, 'c') ]
+25  A: 
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessary.

See: items(), iteritems()

Devin Jeanpierre
-1: Forgot to quote the documentation: http://docs.python.org/library/stdtypes.html#dict.items
S.Lott
Seriously? -1 for that? Come on...
Paolo Bergantino
I'll put the link up there, but imho it's useless. As far as I'm concerned, my job isn't to cite sources, but to put information out in googleable form. That is to say, if the code examples aren't clear or need more explanation, now the question-asker knows how and where to look for more detail.
Devin Jeanpierre
Check what the downarrow says when you put your mouse over it: "This answer is not helpful." Is this answer not helpful? If you think he left out the docs and thats important then don't upvote it, but a downvote is downright wrong here.
Paolo Bergantino
+1  A: 
[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]
Robert Rossney
"[(k,v) for (k,v) in d.iteritems()]" is a terrible equivalent to d.items()
Devin Jeanpierre
+3  A: 

What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>>
Barry Wark
+5  A: 

You can use the use list comprehensions.

[(k,v) for k,v in a.iteritems()]

will get you [ ('a', 1), ('b', 2), ('c', 3) ] and

[(v,k) for k,v in a.iteritems()]

the other example.

Read more about list comprehensions if you like, it's very interesting what you can do with them.

mpeterson
A: 
>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]
cartman
+4  A: 

since no one else did, I'll add py3k versions:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]
SilentGhost