简体   繁体   中英

What is the difference between list / array representation [] and {}?

What is the difference between :

dictionary = []

and

dictionary = {}

assuming dictionary has string contents ?

In the first case, you're making a list whereas the other you're making a dict . list objects are sequences whereas dict objects are mappings . Have a look at the python types page.

Basically, lists "map" sequential integers (starting at 0) to some object. In that way, they behave a lot more like a dynamic array in other languages. In fact, Cpython implements them as overallocated arrays in C.

dict map hashable keys to an object. They're implemented using hash tables.


Also note that starting from python2.7, you can use the {} to create sets as well which are another (fundamental) type. Review:

[] #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. 

On python 2.x

>>> type([])
<type 'list'>
>>> type({})
<type 'dict'>
>>>

On python 3.x

>>> type([])
<class 'list'>
>>> type({})
<class 'dict'>
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM