python – Converting Dictionary to List?

python – Converting Dictionary to List?


Does the trick.

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]

python – Converting Dictionary to List?

Your problem is that you have key and value in quotes making them strings, i.e. youre setting aKey to contain the string key and not the value of the variable key. Also, youre not clearing out the temp list, so youre 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 dont need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you dont 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.

Leave a Reply

Your email address will not be published. Required fields are marked *