Reputation: 2088
I wanted to create a list of dictionaries in python. The usual way of creating a list worked for me. That is 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.
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
Upvotes: 2
Views: 154
Reputation: 2974
You're missing a dictionary creation in your list comprehension:
mylist = [{a:a} for a in range(10)]
Upvotes: 3
Reputation: 238957
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:
In [8]: type(myset)
Out[8]: dict
In this example, {
and }
denote dictionary comprehension, not set comprehension.
Upvotes: 6