预计阅读本页时间:-
Dictionaries
Apart from lists, dictionaries are perhaps the most flexible built-in data type in Python. If you think of lists as ordered collections of objects, you can think of dictionaries as unordered collections; the chief distinction is that in dictionaries, items are stored and fetched by key, instead of by positional offset.
Being a built-in type, dictionaries can replace many of the searching algorithms and data structures you might have to implement manually in lower-level languages—indexing a dictionary is a very fast search operation. Dictionaries also sometimes do the work of records and symbol tables used in other languages, can represent sparse (mostly empty) data structures, and much more. Here’s a rundown of their main properties. Python dictionaries are:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Accessed by key, not offset
Dictionaries are sometimes called associative arrays or hashes. They associate a set of values with keys, so you can fetch an item out of a dictionary using the key under which you originally stored it. You use the same indexing operation to get components in a dictionary as you do in a list, but the index takes the form of a key, not a relative offset.
Unordered collections of arbitrary objects
Unlike in a list, items stored in a dictionary aren’t kept in any particular order; in fact, Python randomizes their left-to-right order to provide quick lookup. Keys provide the symbolic (not physical) locations of items in a dictionary.
Variable-length, heterogeneous, and arbitrarily nestable
Like lists, dictionaries can grow and shrink in-place (without new copies being made), they can contain objects of any type, and they support nesting to any depth (they can contain lists, other dictionaries, and so on).
Of the category “mutable mapping”
Dictionaries can be changed in-place by assigning to indexes (they are mutable), but they don’t support the sequence operations that work on strings and lists. Because dictionaries are unordered collections, operations that depend on a fixed positional order (e.g., concatenation, slicing) don’t make sense. Instead, dictionaries are the only built-in representatives of the mapping type category (objects that map keys to values).
Tables of object references (hash tables)
If lists are arrays of object references that support access by position, dictionaries are unordered tables of object references that support access by key. Internally, dictionaries are implemented as hash tables (data structures that support very fast retrieval), which start small and grow on demand. Moreover, Python employs optimized hashing algorithms to find keys, so retrieval is quick. Like lists, dictionaries store object references (not copies).
Table 8-2 summarizes some of the most common and representative dictionary operations (again, see the library manual or run a dir(dict) or help(dict) call for a complete list—dict is the name of the type). When coded as a literal expression, a dictionary is written as a series of key:value pairs, separated by commas, enclosed in curly braces.[24] An empty dictionary is an empty set of braces, and dictionaries can be nested by writing one as a value inside another dictionary, or within a list or tuple.
Table 8-2. Common dictionary literals and operations
Operation
Interpretation
D = {}
Empty dictionary
D = {'spam': 2, 'eggs': 3}
Two-item dictionary
D = {'food': {'ham': 1, 'egg': 2}}
Nesting
D = dict(name='Bob', age=40)
D = dict(zip(keyslist, valslist))
D = dict.fromkeys(['a', 'b'])
Alternative construction techniques:
keywords, zipped pairs, key lists
D['eggs']
D['food']['ham']
Indexing by key
'eggs' in D
Membership: key present test
D.keys()
D.values()
D.items()
D.copy()
D.get(key, default)
D.update(D2)
D.pop(key)
Methods: keys,
values,
keys+values,
copies,
defaults,
merge,
delete, etc.
len(D)
Length: number of stored entries
D[key] = 42
Adding/changing keys
del D[key]
Deleting entries by key
list(D.keys())
D1.keys() & D2.keys()
Dictionary views (Python 3.0)
D = {x: x*2 for x in range(10)}
Dictionary comprehensions (Python 3.0)
[24] As with lists, you won’t often see dictionaries constructed using literals. Lists and dictionaries are grown in different ways, though. As you’ll see in the next section, dictionaries are typically built up by assigning to new keys at runtime; this approach fails for lists (lists are commonly grown with append instead).