What is the dictionary datatype in Python? How to use it? Some key points and several examples of its usage.
Jump to the cheat sheet
Key points
- Dictionary is a commonly used collection datatype in Python; the others being lists, sets, and tuples.
- A dictionary is essentially a set of key-value pairs, where, the keys should be unique and immutable.
- A dictionary is mutable, i.e., it can be modified in place after it is created. We can add, remove or update items in a dictionary.
- Keys could be of any immutable data type, i.e., string, number, or even a tuple of immutable objects. [Note: Immutable objects are objects which cannot be modified in place once they are created. Python's built-in immutable objects include numbers, strings, and tuples].
- Dictionaries are indexed using their keys.
- Dictionaries are created using a pair of curly braces, i.e., {}, or by using the dict() constructor.
- We can create and initialize a dictionary with items by adding a comma-separated list of key-value pairs within the curly braces. The 'dict' constructor also takes an optional iterable, mapping, or keyword arguments as input.
- For examples on how to create a dictionary, add elements, update elements, remove elements, etc, see the cheat sheet.
Cheat sheet
Useful resources and references
from Planet Python
via read more
No comments:
Post a Comment