The data type dictionary falls under mapping.
- It is a mapping between a set of keys and a set of values.
- The key-value pair is called an item.
- A key is separated from its value by a colon(:) and consecutive items are separated by commas.
- Items in dictionaries are unordered, so we may not get back the data in the same order in which we had entered the data initially in the dictionary.
Creating a dictionary
- To create a dictionary, the items entered are separated by commas and enclosed in curly braces.
- Each item is a key value pair, separated through colon (:).
- The keys in the dictionary must be unique and should be of any immutable data type, i.e., number, string or tuple.
- The values can be repeated and can be of any data type.
Example:
Accessing items in a dictionary
The items of a dictionary are accessed via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value.
Example:
Dictionaries are Mutable
Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created.
Adding a new item
Example:
Modifying an existing item
The existing dictionary can be modified by just overwriting the key-value pair.
Example: