[英]Python - Creating a list of dictionaries
I wanted to create a list of dictionaries in python. 我想在python中创建一个字典列表。 The usual way of creating a list worked for me.
创建列表的常用方法对我有用。 That is
mylist = [{1:1},{2:2}]
那是
mylist = [{1:1},{2:2}]
However, when I tried creating it using a comprehension over range()
function, mylist = [a:a for a in range(10)]
I get syntax error. 但是,当我尝试使用
range()
函数的理解来创建它时, mylist = [a:a for a in range(10)]
我得到语法错误。
But to my surprise, if I construct a set in the same manner, it works as expected. 但令我惊讶的是,如果我以相同的方式构建一个集合,它会按预期工作。
myset = {a:a for a in range(10)}
May I know why this is so? 我可以知道为什么会这样吗? I am using Python3
我正在使用Python3
I think you want something like this: 我想你想要这样的东西:
mylist = [{a:a} for a in range(10)]
You forgot about {
and }
. 你忘记了
{
和}
。
In the second example, your myset
is a dict, not a set: 在第二个例子中,你的
myset
是一个dict,而不是一个集合:
In [8]: type(myset)
Out[8]: dict
In this example, {
and }
denote dictionary comprehension , not set comprehension. 在这个例子中,
{
和}
表示字典理解 ,而不是设置理解。
您在列表理解中缺少字典创建:
mylist = [{a:a} for a in range(10)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.