How can I convert a dictionary into a list of tuples?

Posted on

Question :

How can I convert a dictionary into a list of tuples?

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') ]
Asked By: mike


Answer #1:

>>> 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.1 Sort it or organize it as necessary.

See: items(), iteritems()

In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a “view” into the dictionary items. See the What’s New document for Python 3.0, and the new documentation on views.

1: Insertion-order preservation for dicts was added in Python 3.7

Answered By: Devin Jeanpierre

Answer #2:

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')]
Answered By: SilentGhost

Answer #3:

You can 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.

Answered By: mpeterson

Answer #4:

Create a list of namedtuples

It can often be very handy to use namedtuple. For example, you have a dictionary of ‘name’ as keys and ‘score’ as values like:

d = {'John':5, 'Alex':10, 'Richard': 7}

You can list the items as tuples, sorted if you like, and get the name and score of, let’s say the player with the highest score (index=0) very Pythonically like this:

>>> player = best[0]

>>> player.score

How to do this:

list in random order or keeping order of collections.OrderedDict:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

in order, sorted by value (‘score’):

import collections
Player = collections.namedtuple('Player', 'score name')

sorted with lowest score first:

worst = sorted(Player(v,k) for (k,v) in d.items())

sorted with highest score first:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
Answered By: Remi

Answer #5:

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


[(v,k) for (k,v) in d.iteritems()]
Answered By: Robert Rossney

Answer #6:

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')]
Answered By: Barry Wark

Answer #7:

These are the breaking changes from Python 3.x and Python 2.x

For Python3.x use

dictlist = []
for key, value in dict.items():
    temp = [key,value]

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
Answered By: Dheeraj M Pai

Answer #8:

>>> 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')]
Answered By: ismail

Leave a Reply

Your email address will not be published.