tags:

views:

128

answers:

1

Using Python V2.5.4, I am trying to create a Python dictionary from a stored list. This first method works

>>>myList=[]
>>>myList.append('Prop1')
>>>myList.append('Prop2')
>>>myDict = dict([myList])

However, the following method does not work

>>>myList2=['Prop1','Prop2','Prop3','Prop4']
>>>myDict2 = dict([myList2])
ValueError: dictionary update sequence element #0 has length 3; 2 is required

So I am wondering why the first method using append works but the second method doesn't work? Is there a difference between myList and myList2?

Edit

Checked again myList2 actually has more than two elements. Updated second example to reflect this. Thanks to the comments.

+6  A: 

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
Daniel Pryden
Thanks just as I needed and now I realize if I have a list of keys I can create the dictionary with: myDict = dict(zip(myList,zeros(len(myList)))). If I don't have the values yet.
Azim
@Azim: Yes, that's a good approach. The point is, when you create the `dict`, you need to provide *some* value for each key. You can always go back and change the value later.
Daniel Pryden