I am trying to create a Python dictionary from a stored list. This first method works
>>> myList = []
>>> myList.append(\'Prop1\')
>>&
You're doing it wrong.
The dict()
constructor doesn't take a list of items (much less a list containing a single list of items), it takes an iterable of 2-element iterables. So if you changed your code to be:
myList = []
myList.append(["mykey1", "myvalue1"])
myList.append(["mykey2", "myvalue2"])
myDict = dict(myList)
Then you would get what you expect:
>>> myDict
{'mykey2': 'myvalue2', 'mykey1': 'myvalue1'}
The reason that this works:
myDict = dict([['prop1', 'prop2']])
{'prop1': 'prop2'}
Is because it's interpreting it as a list which contains one element which is a list which contains two elements.
Essentially, the dict
constructor takes its first argument and executes code similar to this:
for key, value in myList:
print key, "=", value