Difference between dict and set (python)

声明和定义

列表 list

一个数据结构,可以将一组数据存放其中,并进行处理 , 用 方括号 [ ] 表示
friends = ['John', 'Mike', 'Mary', 'Zhang San']

字典dictionary

创建空字典,用花括号 {} 或者函数 dict()

dict_0 = {} # create an empty dictionary
dict_1 = dict ()()# create an empty dictionary

集合set

集合的创建:花括号 至少一个元素 或者 set()

创建一个空集合
set_0 = set()

创建一个非空集合
set_1 = {'John', 'Mary', 'Mike', 'Ada'}

 

 

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 the same syntax for both sets and 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?

 

回答1

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.

 

回答2

The fact that {} is used for an empty dictionary and not for an empty set has largely historical reasons. The syntax {'a': 100, 'b': 200} for dictionaries has been around since the beginning of Python. The syntax {1, 2, 3} for sets was introduced with Python 2.7. Since {} has been used for such a long time it will stay as the way to define an empty dictionary. If Python would have had the new set syntax since the beginning, likely an empty set would be defined with {} and an empty dictionary with {:}.

 

Python Sets vs Lists

It depends on what you are intending to do with it.

Sets are significantly faster when it comes to determining if an object is present in the set (as in x in s), but are slower than lists when it comes to iterating over their contents.

You can use the timeit module to see which is faster for your situation.

 

Python: List vs Dict for look up table

Speed

Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.

Memory

Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.

If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(121)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2014-10-29 Exception.StackTrace
点击右上角即可分享
微信分享提示