289

I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.

#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"

#lists
temp = []
dictList = []

#My attempt:
for key, value in dict.iteritems():
    aKey = key
    aValue = value
    temp.append(aKey)
    temp.append(aValue)
    dictList.append(temp) 
    aKey = ""
    aValue = ""

That's my attempt at it... but I can't work out what's wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
Federer
  • 33,677
  • 39
  • 93
  • 121
  • 7
    `sum(dict.items(), ())` – Natim Nov 21 '16 at 18:36
  • 28
    Note that in Python 3, `dict.items()` `dict.keys()` and `dict.values()` returns a `Dictionary object` which, not supporting indexing, is not a real list. A real list can be obtained by `list(dict.values())`. – ZhaoGang Sep 21 '18 at 02:59

7 Answers7

552
dict.items()

Does the trick.

(For Python 2 only)

Cardin
  • 5,148
  • 5
  • 36
  • 37
Björn
  • 29,019
  • 9
  • 65
  • 81
  • 25
    I knew there'd be some ridiculous Pythonic way of doing this, thank you very much indeed. I just find the documentation for Python rather hard to read! – Federer Nov 05 '09 at 09:44
  • 1
    You can always use *help(dict)* on the Python command line and replace *dict* with the troublesome object to see a list of its helper methods etc., e.g. *items(...) D.items() -> list of D's (key, value) pairs, as 2-tuples* – Aaron Newton Jun 03 '12 at 06:10
  • 40
    He wants a flat list, items() produces a list of tuples. – Ajith Antony Dec 22 '12 at 12:12
  • He never said he wanted a flat list, he only said he wanted a list. A list of tuples is a valid python list. – codetaku Nov 19 '14 at 16:43
  • 54
    To get a flat list, use dict.values() instead. – Andy Fraley Apr 11 '16 at 15:55
  • 5
    When I tried to access the list resulting from `dictlist=dict.items()`, I then got an error trying to access it like a list: dictlist[i][1]. Python3 doc says: ~~~~ "The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes." ~~~~ One more step was required to make it work: ---- [ (item[0],item[1]) for item in dict.items() ] – Craig Hicks Oct 05 '17 at 06:05
  • 51
    For python3 use `list(dict.values())` – Demetris Jun 07 '18 at 12:41
  • 1
    dict.items() does not return a list. Running this code: ```mydict = {'value1':['a','b','c'],'value2':['a','b','c']} mylist= mydict.items() print(type(mylist))``` prints out the value: ``````. – Jeff Gruenbaum Jun 15 '20 at 15:39
  • 1
    @JeffGruenbaum Read the comment right above yours – Arthur Tacca Dec 06 '21 at 11:20
271

Converting from dict to list is made easy in Python. Three examples:

>> d = {'a': 'Arthur', 'b': 'Belling'}

>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]

>> d.keys()
['a', 'b']

>> d.values()
['Arthur', 'Belling']
Akseli Palén
  • 27,244
  • 10
  • 65
  • 75
  • Is it possible to specify the order of `values()`? Is the order of the values of a standard dict even defined? – Michael Scheper Aug 22 '16 at 23:10
  • 2
    @MichaelScheper [The order of standard dict is not specified](http://stackoverflow.com/a/9001529/638546) and the order of values can be in different from insertion order. However, one could [sort the lists above](https://wiki.python.org/moin/HowTo/Sorting) or use **OrderedDict** (see the first link). – Akseli Palén Aug 24 '16 at 08:49
  • 20
    It seems that in Python3, you must use list(d.items()), list(d.keys()) and list(d.values()) – MACE Mar 10 '20 at 13:15
  • 1
    I always seem to end up with dict_values at the start of each row of the list. – user3520245 Jun 15 '20 at 10:58
  • @MichaelScheper dictionaries don't have a stable ordering, if you want to order by keys then use ``[v for k, v in sorted(d.items(), key=lambda pair: pair[0])]``. It's a shame Python doesn't have tuple unpacking for lambdas – Facundo Mar 30 '21 at 17:14
  • In Python3 dict.items(), dict.keys() and dict.values() actually return [dictionary views](https://docs.python.org/3/library/stdtypes.html#dict-views) instead of lists. Dictionary views change dynamically with the dict itself, and comparison operators can have unexpected behaviour. If you want a list, do as @MACE suggests. – Márton Kardos Jul 05 '22 at 13:10
183

Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.

To fix your code, try something like:

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

You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.

Or just use dict.items() as has been suggested.

David Webb
  • 190,537
  • 57
  • 313
  • 299
  • 3
    Correct answer due to explaining what I was doing wrong. As you can tell, I'm fairly knew to Python and any explanations are greatly appreciated. Cheers! – Federer Nov 05 '09 at 09:46
  • 2
    If you use append lists like this, you are producing an list of lists. What he wanted was a flat list, for which you would use extend() like in Shay's answer. – Ajith Antony Dec 22 '12 at 12:22
  • 2
    He never said that, Ajith. A list of lists is a valid python list, and a much better interpretation of a "dictionary" than a flat list containing only non-list values. A list of lists is at least capable of showing keys and values still grouped together. – codetaku Nov 19 '14 at 16:42
  • 9
    It says `'dict' object has no attribute 'iteritems'` Can you update the answer for python 3.6 please. – Trect Jun 30 '18 at 11:22
  • 4
    `dict(iterable) -> new` dictionary initialized as if via: `d = {} for k, v in iterable: d[k] = v` so please use `items()` instead of `'iteritems'` – Anu Aug 16 '19 at 14:11
  • Hi As @Trect said it is error so to avoid is use dict.items(),Like this and it would work dictlist=[] for key, value in dictionary.items(): temp = [key,value] dictlist.append(temp) print(dictlist) – bilalmohib Jan 26 '22 at 07:48
78

You should use dict.items().

Here is a one liner solution for your problem:

[(k,v) for k,v in dict.items()]

and result:

[('Food', 'Fish&Chips'), ('2012', 'Olympics'), ('Capital', 'London')]

or you can do

l=[]
[l.extend([k,v]) for k,v in dict.items()]

for:

['Food', 'Fish&Chips', '2012', 'Olympics', 'Capital', 'London']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Shay
  • 1,245
  • 7
  • 14
46
 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.

Zitrax
  • 19,036
  • 20
  • 88
  • 110
Martin DeMello
  • 11,876
  • 7
  • 49
  • 64
29

Probably you just want this:

dictList = dict.items()

Your approach has two problems. For one you use key and value in quotes, which are strings with the letters "key" and "value", not related to the variables of that names. Also you keep adding elements to the "temporary" list and never get rid of old elements that are already in it from previous iterations. Make sure you have a new and empty temp list in each iteration and use the key and value variables:

for key, value in dict.iteritems():
    temp = []
    aKey = key
    aValue = value
    temp.append(aKey)
    temp.append(aValue)
    dictList.append(temp)

Also note that this could be written shorter without the temporary variables (and in Python 3 with items() instead of iteritems()):

for key, value in dict.items():
    dictList.append([key, value])
sth
  • 222,467
  • 53
  • 283
  • 367
5

If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()

Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:

headers = ['Capital', 'Food', 'Year']
countries = [
    ['London', 'Fish & Chips', '2012'],
    ['Beijing', 'Noodles', '2008'],
]

for olympics in countries:
    print zip(headers, olympics)

gives

[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]

Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.

Morgan
  • 4,143
  • 27
  • 35