English 中文(简体)
Converting Dictionary to List? [duplicate]

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"

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?


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.


Does the trick.

(For Python 2 only)

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 ]

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

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

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

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)


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

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

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 ]="...