Книга: Fedora™ Unleashed, 2008 edition
Dictionaries
Dictionaries
Unlike lists, dictionaries are collections with no fixed order. Instead, they have a key (the name of the element) and a value (the content of the element), and Python places them wherever it needs to for maximum performance. When defining dictionaries, you need to use braces ({ }
) and colons (:
). You start with an opening brace and then give each element a key and a value, separated by a colon, like this:
>>> mydict = { "perl" : "a language", "php" : "another language" }
>>> mydict
{'php': 'another language', 'perl': 'a language'}
This example has two elements, with keys perl
and php
. However, when the dictionary is printed, we find that php
comes before perl
— Python hasn't respected the order in which they were entered. You can index into a dictionary using the normal code:
>>> mydict["perl"] 'a language'
However, because a dictionary has no fixed sequence, you cannot take a slice, or index by position.
Like lists, dictionaries are mutable and can also be nested; however, unlike lists, you cannot merge two dictionaries by using +
. A key is used to locate dictionary elements, so having two elements with the same key would cause a clash. Instead, you should use the update()
method, which merges two arrays by overwriting clashing keys.
You can also use the keys()
method to return a list of all the keys in a dictionary.