开发者

Python dictionary creation error

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])
V开发者_如何学CalueError: 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜