What is the difference between curly brace and square bracket in Python?

匆匆过客 提交于 2019-11-29 19:51:32

Curly braces create dictionaries or sets. Square brackets create lists.

They are called literals; a set literal:

aset = {'foo', 'bar'}

or a dictionary literal:

adict = {'foo': 42, 'bar': 81}
empty_dict = {}

or a list literal:

alist = ['foo', 'bar', 'bar']
empty_list = []

To create an empty set, you can only use set().

Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.

There is also the tuple type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:

atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')

Note the comma in the another_tuple definition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tuple is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.

See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.

Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.

They create different types.

>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>

These two braces are used for different purposes. If you just want a list to contain some elements and organize them by index numbers (starting from 0), just use the [] and add elements as necessary. {} are special in that you can give custom id's to values like a = {"John": 14}. Now, instead of making a list with ages and remembering whose age is where, you can just access John's age by a["John"].

The [] is called a list and {} is called a dictionary (in Python). Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.

However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the same order as before. Hence, when you go through each value one by one, it won't be in the order you expect. There is a special dictionary to get around this, but you have to add this line from collections import OrderedDict and replace {} with OrderedDict(). But, I don't think you will need to worry about that for now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!