Access dictionary elements
To work with the elements of a dictionary, they must be accessible somehow. If you can't get them by index, how can you get them?
The value is retrieved from the dictionary by specifying the corresponding key in square brackets (
[]
).
For example, displaying the capital of Abkhazia from the dictionary created in the previous task:
print(dict_country['Abkhazia'])
If you refer to a key that is not in the dictionary, Python throws an exception:
print(dict_country['Russia'])
Traceback (most recent call last ): File "<...>", line ..., in <module>
print(dict_country[& #39;Russia'])
KeyError: 'Russia' ;
Adding elements to the dictionary
Adding an entry to an existing dictionary is as simple as assigning a new key and value:
dict_country['Russia'] = 'Moscow'
Updating a dictionary entry
If you want to update an entry, you can simply assign a new value to an existing key:
dict_country['Russia'] = 'Moscow'
Remove entry from dictionary
To delete an entry, use the del
operator, specifying the key to delete:
del dict_country[<key>]
While accessing elements in a dictionary is order independent, Python ensures that the order of elements in a dictionary is preserved. When displayed, the elements will be displayed in the order in which they were defined, and the keys will also be repeated in that order. Items added to the dictionary are added at the end. If elements are removed, the order of the remaining elements is preserved.
It should be remembered that the keys of the dictionary, as well as the elements of the dictionary, can be of different types. A dictionary can also have the following content:
d = {42: [2, 3, 6, 7], 2.78: 'bbb', True: 1}
print(d[42][1]) # 3 - to access nested elements, use an additional key or index