Dictionary
is similar to list but more general. In a list, the position have to be
integers but in dictionary the indices can be almost any type. Dictionary can
be defined using dict built-in command.
>>> d = dict() >>> type(d)
You
can think of a dictionary as a mapping between a set of indices and they are
called keys and a set of values. Each key maps to a value. The association of a
key and a value is called key-value or sometimes an item.
A
good example to show a simple use of
dictionary and key-value pair would be that dictionary maps from English to
Italian words. So the keys and the values in this case are all strings.
>>>translator = dict() >>>print trnaslator {}
The curly-brackets or braces represent an empty
dictionary. To add items into an empty dictionary, you can use square brackets.
>>>translator['one'] = 'uno' >>>print translator {'one': 'uno'}
This line creates an item that maps from the key ‘one’
to the value ‘uno’. Using print built-in function we’ve printed out dictionary
again, and we see a key-value pair with a colon between the key and value.
This output format is equal to the input format
because you can create new dictionary in the same way. In our case we will
extend translator dictionary.
translator = {'one': 'uno', 'two': 'due', 'three': 'tre', 'four': 'quattro' , 'five':'cinque', 'six':'sei', 'seven':'sette', 'eight':'otto', 'nine':'nove', 'ten':'dieci'} print translator {'four': 'quattro', 'seven': 'sette', 'five': 'cinque', 'three': 'tre', 'ten': 'dieci', 'eight': 'otto', 'nine': 'nove', 'six': 'sei', 'two': 'due', 'one': 'uno'}
As
you can see after we’ve printed out the translator dictionary the key-value
pairs are not in the same order as we’ve defined in declaration of dictionary.
In general the order of items in the dictionary is very unpredictable. The
reason for that is because the elements of a dictionary are never indexed with
integer indices. Instead, you use the keys to look up the corresponding values.
So let’s look for number five.
>>>print translator['five'] cinque
The
key ‘five’ always maps to the value ‘five’ as defined in dictionary declaration
so order of items doesn’t matter. If key isn’t defined in the dictionary Python
interpreter will return a KeyError for example let’s look for number twenty
three.
>>> print translator[‘twenty three’] KeyError: 'twenty three'
Nema komentara:
Objavi komentar