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?
The straight answer is NO. You can not have duplicate keys in a dictionary in 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.
[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<> .
dict.items()
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With