3.3 定义字典

我们可以使用键-值对格式创建字典。有两种方式做这个,我们通常会使用第一个:

  1. >>> pos = {'colorless': 'ADJ', 'ideas': 'N', 'sleep': 'V', 'furiously': 'ADV'}
  2. >>> pos = dict(colorless='ADJ', ideas='N', sleep='V', furiously='ADV')

请注意,字典的键必须是不可改变的类型,如字符串和元组。如果我们尝试使用可变键定义字典会得到一个TypeError

  1. >>> pos = {['ideas', 'blogs', 'adventures']: 'N'}
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. TypeError: list objects are unhashable