Python dictionary creation error

99封情书 提交于 2019-12-01 17:58:57

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!