Python dictionary creation error

I am trying to create a Python dictionary from a saved 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 wonder why the first method uses append, but the second method does not work? Is there any difference between myList and myList2 ?

Edit

Checked again myList2 Actually has more than two elements. Updated second example to reflect this.

+5
python
source share
1 answer

You are doing it wrong.

The dict() constructor does not accept a list of elements (and especially a list containing one list of elements), it accepts the iterability of iterations of 2 elements. Therefore, if you change your code:

 myList = [] myList.append(["mykey1", "myvalue1"]) myList.append(["mykey2", "myvalue2"]) myDict = dict(myList) 

Then you get what you expect:

 >>> myDict {'mykey2': 'myvalue2', 'mykey1': 'myvalue1'} 

The reason this works:

 myDict = dict([['prop1', 'prop2']]) {'prop1': 'prop2'} 

This is because he interprets it as a list containing one item, which is a list that contains two items.

Essentially, the dict constructor takes its first argument and executes code similar to this:

 for key, value in myList: print key, "=", value 
+13
source share

All Articles