Several ways to create a dictionary in Python summarize the of recommendations

  • 2020-05-30 20:32:26
  • OfStack

1. Traditional text expressions:

>>> d={'name':'Allen','age':21,'gender':'male'}
>>> d
{'age': 21, 'name': 'Allen', 'gender': 'male'}

This is convenient if you can spell out the whole dictionary in advance.

2. Dynamically assign key values:

>>> d={}
>>> d['name']='Allen'
>>> d['age']=21
>>> d['gender']='male'
>>> d
{'age': 21, 'name': 'Allen', 'gender': 'male'}

If you need to dynamically create a field of a dictionary one time, this approach is appropriate.

Unlike lists, dictionaries can't be copied by offsets, but can only be read or assigned by keys, so you can also assign a value to a dictionary like this. Of course, accessing a key that doesn't exist will give you an error:

>>> 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>
KeyError: 2

3. Dictionary key table

>>> c = dict(name='Allen', age=14, gender='male')
>>> c
{'gender': 'male', 'name': 'Allen', 'age': 14}

This form is very popular because it is grammatically simple and error-free.

This form requires less code than a constant, but the keys must all be strings, so the following code will report an error:

>>> c = dict(name='Allen', age=14, gender='male', 1='abcd')
SyntaxError: keyword can't be an expression

4. Table of dictionary key tuples

>>> e=dict([('name','Allen'),('age',21),('gender','male')])
>>> e
{'age': 21, 'name': 'Allen', 'gender': 'male'}

This is useful if you need to build up a sequence of keys and values as the program runs.

5. All keys have the same value or are given the initial value:

>>> f=dict.fromkeys(['height','weight'],'normal')
>>> f
{'weight': 'normal', 'height': 'normal'}

Related articles: