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

前端 未结 3 1227
闹比i
闹比i 2020-12-12 12:44

what is the difference between curly brace and square bracket in python?

A ={1,2}
B =[1,2]

when I print A and B o

3条回答
  •  自闭症患者
    2020-12-12 13:31

    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.

提交回复
热议问题