Several methods for creating dictionaries in Python (recommended) and several python Methods
1. Traditional text expressions:
>>> d={'name':'Allen','age':21,'gender':'male'}>>> d{'age': 21, 'name': 'Allen', 'gender': 'male'}
This method is very convenient if you can spell out the entire dictionary in advance.
2. dynamically allocate key values:
>>> d={}>>> d['name']='Allen'>>> d['age']=21>>> d['gender']='male'>>> d{'age': 21, 'name': 'Allen', 'gender': 'male'}
This method is suitable if you need to dynamically create a dictionary field at a time.
The dictionary is different from the list. It cannot be copied by offset. It can only be read or assigned by key. Therefore, you can assign values to the dictionary as follows. Of course, an error is returned when you access a key that does not exist:
>>> d[1]='abcd'>>> d{1: 'abcd', 'age': 21, 'name': 'Allen', 'gender': 'male'}>>> d[2]Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> d[2]KeyError: 2
3. dictionary key value table
>>> c = dict(name='Allen', age=14, gender='male')>>> c{'gender': 'male', 'name': 'Allen', 'age': 14}
This form of syntax is simple and error-prone, so it is very popular.
This form requires less code than a constant, but the keys must be strings, so the following code reports an error:
>>> c = dict(name='Allen', age=14, gender='male', 1='abcd')SyntaxError: keyword can't be an expression
4. dictionary key-value tuples
>>> e=dict([('name','Allen'),('age',21),('gender','male')])>>> e{'age': 21, 'name': 'Allen', 'gender': 'male'}
This method is useful if you need to gradually build keys and values into a sequence when the program is running.
5. The values of all keys are the same or the initial values are assigned:
>>> f=dict.fromkeys(['height','weight'],'normal')>>> f{'weight': 'normal', 'height': 'normal'}
The summary (recommended) of the several methods used to create a dictionary in Python is the full content shared by the editor. I hope you can give us a reference and support for the help house.