[python] Converting Dictionary to List?

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?

This question is related to python list dictionary

The answer is


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.


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

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

dict.items()

Does the trick.


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


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python