of identifying keys and specific values, one for each key. An item in a dictionary is a
key:value pair that represents one entry. A dictionary is modifiable; new entries can be
added, existing entries can be removed and existing entries can be modified by changing
the value associated with a key. A dictionary is defined using a left curly bracket ‘{’ at the
start and a right curly bracket ‘}’ at the end. When written out in full the key and value of
a pair is linked by a colon ‘:’ and different pairs are separated with commas. For example,
The last dictionary above maps the string ‘Ala’ to the value 71.07 and the string ‘Arg’
gets mapped to the value 156.18. Although a dictionary value can be of any type, a key in
a dictionary must be hashable (not internally modifiable), in the same way as an item in a
set. Not only does this guarantee that the keys of the dictionary don’t repeat, it also
provides an efficient look-up mechanism. Neither the keys nor the values have to all be of
the same data type, although in use they often are; it is quite common for keys to be
strings. You can think of an English dictionary as being a map from words to definitions,
in which case both the keys (the words) and the values (the definitions of each word) are
text strings. Though, one difference is that an English dictionary is ordered
(alphabetically) but a Python dictionary is not.
After having described the major collection types, a question arises as to why we need
the tuple data type at all, since a list is everything that a tuple is and more. There are three
basic reasons. The first reason is that tuples are more efficient computationally, although
normally that is not a big issue. The second reason is that a program might want to return a
tuple rather than a list to users because it does not want the collection to be modified; an
example would be (latitude, longitude) coordinates where both items go together to give a
meaningful outcome. The third reason is that, as mentioned above, lists can be modified
and so are not hashable. Hence, lists cannot be used as items in a set or as keys in
dictionaries, whereas tuples can. You can think of a tuple as a frozen list.
Although sets are modifiable and so not hashable, there is a variant of sets that is, and
these are called frozen sets. Accordingly, a frozen set is an unordered collection of items,
without repetition, and which cannot be modified. To create a frozen set you use the
nomenclature frozenset(…) instead of set(..). You can think of the relationship between
sets and frozen sets as being the same as the relationship between lists and tuples. There
are no inbuilt frozen dictionaries in Python, although you could add them yourself if you
were really keen (by making a custom object which inherits properties of a dictionary, but
where some of the innards are redefined).
Do'stlaringiz bilan baham: