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') ]
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') ]
>>> 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()
[(k,v) for (k,v) in d.iteritems()]
and
[(v,k) for (k,v) in d.iteritems()]
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')]
>>>
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.
>>> 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')]
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')]