Skip to content
Fix Code Error

Converting Dictionary to List?

March 13, 2021 by Code Error
Posted By: Anonymous

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?

Solution

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.

Answered By: Anonymous

Related Articles

  • C# Only allow one class to call a different class's setter…
  • Sort table rows In Bootstrap
  • How do I merge two dictionaries in a single expression…
  • How do I include certain conditions in SQL Count
  • Convert Python dict into a dataframe
  • Ember computed property doesn't update when dependent…
  • Issue Iterating Over Ember.js Object in Template
  • error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’…
  • Uncaught (in promise) TypeError: states.filter is not a…
  • DataTable draw daterange from vaadin-date-picker in polymer

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

CSS3 Rotate Animation

Next Post:

What is the best way to conditionally apply a class?

Leave a Reply Cancel reply

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

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error