Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

dictionary - Difference between dict and set (python)

So, I know that this,

a = {}  # dict

constructs an empty dictionary. Now, I also picked up that this,

b = {1, 2, 3}  # set

creates a set. This can easily be verified, as,

>>>print(type(a))
<class 'dict'>

>>>print(type(b))
<class 'set'>

While I understand what it does, I fail to see why we use 'set notation' for empty dictionaries. I tried to find some more information about the logic behind this in the set and dict sections of the manual, but sadly, I got nothing out of it.

Could anyone explain to me why we do this in this way? Is it for historical reasons, or am I missing something blatantly obvious?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There were no set literals in Python 2, historically curly braces were only used for dictionaries. Sets could be produced from lists (or any iterables):

set([1, 2, 3])
set([i for i in range(1, 3)])

Python 3 introduced set literals and comprehensions (see PEP-3100) which allowed us to avoid intermediate lists:

{1, 2, 3}
{i for i in range(1, 3)}

The empty set form, however, was reserved for dictionaries due to backwards compatibility. References from [Python-3000] sets in P3K? states:

I'm sure we can work something out --- I agree, {} for empty set and {:} for empty dict would be ideal, were it not for backward compatibility. I liked the "special empty object" idea when I first wrote the PEP (i.e., have {} be something that could turn into either a set or dict), but one of the instructors here convinced me that it would just lead to confusion in newcomers' minds (as well as being a pain to implement).

The following message describes these rules better:

I think Guido had the best solution. Use set() for empty sets, use {} for empty dicts, use {genexp} for set comprehensions/displays, use {1,2,3} for explicit set literals, and use {k1:v1, k2:v2} for dict literals. We can always add {/} later if demand exceeds distaste.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...