257

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')]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
mike
  • 46,876
  • 44
  • 102
  • 112
  • 11
    `[tuple(reversed(x)) for x in d.items()]` – garej Jan 05 '18 at 09:10
  • 2
    @garej: Given `x` is already a `tuple` in your code (it's the nature of `items` to produce an iterable of `tuple`s), it would be simpler/faster to just do `[x[::-1] for x in d.items()]`; the reversing slice directly constructs a reversed `tuple` of the proper size rather than having the `tuple` constructor iteratively populate (with overallocation and resizing at the end) a `tuple` from a `reversed` iterator. – ShadowRanger Mar 27 '19 at 22:46
  • @ShadowRanger, you are right. I just wanted to be explicit that it is not always a need for `k, v` pattern in such cases. – garej Mar 28 '19 at 05:11

13 Answers13

410
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]

For Python 3.6 and later, the order of the list is what you would expect.

In Python 2, you don't need list.

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Devin Jeanpierre
  • 92,913
  • 4
  • 55
  • 79
67

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
  • 307,395
  • 66
  • 306
  • 293
19

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.

Michael Ohlrogge
  • 10,559
  • 5
  • 48
  • 76
mpeterson
  • 741
  • 1
  • 7
  • 17
10

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.name
        'Alex'
>>> player.score
         10

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)
Remi
  • 20,619
  • 8
  • 57
  • 41
7
[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
7

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
  • 107,306
  • 24
  • 181
  • 206
5

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]
    dictlist.append(temp)

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)
Trect
  • 2,759
  • 2
  • 30
  • 35
4

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.

Demo:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • This worked for me as an alternative to `collections.OrderedDict()` that works better with multiple versions of Python HTTP Requests lib. Even though I dislike the `zip` function name as being somewhat vague/overloaded. – MarkHu Jun 14 '16 at 19:53
  • Note the `zip`-ification is not a "deep" casting, i.e. if there are nested children, they wont be affected. You might have to roll your own recursion. – MarkHu Jan 14 '17 at 12:48
4

A alternative one would be

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (value, key) tuples
ksha
  • 2,007
  • 1
  • 19
  • 22
4
>>> 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')]
ismail
  • 46,010
  • 9
  • 86
  • 95
3
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list
Harish
  • 157
  • 2
  • 11
  • 3
    Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 23 '16 at 10:09
0

Python3 dict.values() not return a list. This is the example

mydict = {
  "a": {"a1": 1, "a2": 2},
  "b": {"b1": 11, "b2": 22}
}

print(mydict.values())
> output: dict_values([{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}])

print(type(mydict.values()))
> output: <class 'dict_values'>

print(list(mydict.values()))
> output: [{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}]

print(type(list(mydict.values())))
> output: <class 'list'>
Binh Ho
  • 3,690
  • 1
  • 31
  • 31
0
x = {'a': 1, 'b': 2, 'c': 4, 'd':3}   
sorted(map(lambda x : (x[1],x[0]),x.items()),key=lambda x : x[0])

Lets break the above code into steps

step1 = map(lambda x : (x[1],x[0]),x.items())

x[1] : Value
x[0] : Key

Step1 will create a list of tuples containing pairs in the form of (value,key) e.g. (4,'c')

step2 = sorted(step1,key=lambda x : x[0]) 

Step2 take the input of from Step 1 and sort using the 1st value of the tuple