Other Ways to Make Dictionaries

Finally, note that because dictionaries are so useful, more ways to build them have emerged over time. In Python 2.3 and later, for example, the last two calls to the dict constructor (really, type name) shown here have the same effect as the literal and key-assignment forms above them:

{'name': 'mel', 'age': 45}             # Traditional literal expression

D = {}                                 # Assign by keys dynamically
D['name'] = 'mel'
D['age']  = 45

dict(name='mel', age=45)               # dict keyword argument form

dict([('name', 'mel'), ('age', 45)])   # dict key/value tuples form

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

All four of these forms create the same two-key dictionary, but they are useful in differing circumstances:

 

 
  • The first is handy if you can spell out the entire dictionary ahead of time.
  • The second is of use if you need to create the dictionary one field at a time on the fly.
  • The third involves less typing than the first, but it requires all keys to be strings.
  • The last is useful if you need to build up keys and values as sequences at runtime.

We met keyword arguments earlier when sorting; the third form illustrated in this code listing has become especially popular in Python code today, since it has less syntax (and hence there is less opportunity for mistakes). As suggested previously in Table 8-2, the last form in the listing is also commonly used in conjunction with the zip function, to combine separate lists of keys and values obtained dynamically at runtime (parsed out of a data file’s columns, for instance). More on this option in the next section.

Provided all the key’s values are the same initially, you can also create a dictionary with this special form—simply pass in a list of keys and an initial value for all of the values (the default is None):

>>> dict.fromkeys(['a', 'b'], 0)
{'a': 0, 'b': 0}

Although you could get by with just literals and key assignments at this point in your Python career, you’ll probably find uses for all of these dictionary-creation forms as you start applying them in realistic, flexible, and dynamic Python programs.

The listings in this section document the various ways to create dictionaries in both Python 2.6 and 3.0. However, there is yet another way to create dictionaries, available only in Python 3.0 (and later): the dictionary comprehension expression. To see how this last form looks, we need to move on to the next section.