同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
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
All four of these forms create the same two-key dictionary, but they are useful in differing circumstances:
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.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏