python Python字典创建错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1615501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:42:58  来源:igfitidea点击:

Python dictionary creation error

pythonpython-2.5

提问by Azim

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

我正在尝试从存储的列表中创建一个 Python 字典。第一种方法有效

>>> 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 myListand myList2?

所以我想知道为什么使用 append 的第一种方法有效,但第二种方法不起作用?有没有之间的差异myListmyList2

Edit

编辑

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

再查一查myList2居然有两个以上的要素。更新了第二个示例以反映这一点。

回答by Daniel Pryden

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:

dict()构造并不需要的项目的列表(更不用说包含的项目的单列表的列表),它需要一个可迭代2元件iterables的。因此,如果您将代码更改为:

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 dictconstructor takes its first argument and executes code similar to this:

本质上,dict构造函数接受它的第一个参数并执行类似于以下的代码:

for key, value in myList:
    print key, "=", value