python – What is the meaning of curly braces?
python – What is the meaning of curly braces?
Curly Braces are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another – kind of like how an English dictionary maps a word to its definition.
Python:
dict = {
a : Apple,
b : Banana,
}
They are also used to format strings, instead of the old C style using %, like:
ds = [a, b, c, d]
x = [has_{} 1.format(d) for d in ds]
print x
[has_a 1, has_b 1, has_c 1, has_d 1]
They are not used to denote code blocks as they are in many C-like languages.
C:
if (condition) {
// do this
}
Update: In addition to Pythons dict
data types Python has (since Python 2.7) set as well, which uses curly braces too and are declared as follows:
my_set = {1, 2, 3, 4}
In Python, curly braces are used to define a dictionary.
a={one:1, two:2, three:3}
a[one]=1
a[three]=3
In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.
for entry in entries:
code....
Theres a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.
from __future__ import braces
python – What is the meaning of curly braces?
In languages like C
curly braces ({}
) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.