有什么区别:
dictionary = []
和
dictionary = {}
假设字典有字符串内容?
请您参考如下方法:
在第一种情况下,您正在制作一个列表,而在另一种情况下您正在制作一个dict。 list 对象是 sequences而 dict 对象是 mappings .看看 python types页面。
基本上,列出“映射”顺序整数(从 0 开始)到某个对象。这样,它们的行为更像其他语言中的动态数组。事实上,Cpython 在 C 中将它们实现为过度分配的数组。
dict 将可散列键映射到一个对象。它们是使用哈希表实现的。
另请注意,从 python2.7 开始,您还可以使用 {} 创建集合,这是另一种(基本)类型。评论:
[] #empty list
{} #empty dict
set() #empty set
[1] #list with one element
{'foo':1} #dict with 1 element
{1} #set with 1 element
[1, 2] #list with 2 elements
{'foo':1, 'bar':2} #dict with 2 elements
{1, 2} #set with 2 elements.
