Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"  #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?

like image 985
Federer Avatar asked Nov 05 '09 09:11

Federer


People also ask

Can dictionary have duplicate values Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can you turn a dictionary into a list Python?

In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.

Do dictionaries allow duplicates?

[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .


2 Answers

dict.items() 

Does the trick.

like image 185
Björn Avatar answered Oct 02 '22 20:10

Björn


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'] 
like image 28
Akseli Palén Avatar answered Oct 02 '22 22:10

Akseli Palén