Converting Dictionary to List?

Python Programming

Question or problem about Python programming:

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

#My dictionary
dict = {}

temp = []
dictList = []

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

That’s my attempt at it… but I can’t work out what’s wrong?

How to solve the problem:

Solution 1:

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]

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.

Solution 2:


Does the trick.

Solution 3:

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']

Solution 4:

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.extend([k,v]) for k,v in dict.items()]


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

Solution 5:

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

Hope this helps!