Introduction to Dictionaries in Python:
- A dictionary in Python Programming Language is a container for a set of key-value pairs. The key-value pairs stored in a Python Dictionary maintain the insertion order.
- The other programming language equivalents of a Python dictionary include maps of C++ Standard Library and the associative arrays of the Perl.
Key |
Value |
---|---|
USA |
Washington D.C. |
UK |
London |
Japan |
Tokyo |
France |
Paris |
- The dictionary implementation in Python is provided through the class dict.
- The keys present in a Python dictionary are unique. There will not be any duplicate keys in a Python dictionary. The collection of key space in a Python dictionary is a set i.e., no two keys are same in a set.
- The keys of a Python dictionary should be of immutable types.
- A string literal, a numeric value can all be stored as a key in a Python dictionary. A Python tuple as well can be stored as a key in a Python dictionary for the reason being a string, a numeric value, a tuple are all immutable types.
- However, a python list cannot be stored as a key in a Python dictionary, as a list is a mutable object.
Construction of a Python Dictionary:
Dictionary objects in python are crated by placing key-value pairs inside a pair of braces. |
Creates an empty dictionary. |
Creates a python dictionary as specified in the keyword-argument-list. |
Creates a python dictionary from a mapping object or from another dictionary. |
Creates a python dictionary from an iterable object. |
Methods of the Python Dictionary class:
Retrieves the value associated with dict_key_in parameter, otherwise called a dictionary lookup. |
Returns the value associated with a key in the python dictionary object. |
Deletes a key-value pair as identified by the key. |
The clear() method removes all the items from the dictionary. |
Returns a shallow copy of the Python dictionary object. |
Returns the value associated with a key in the Python dictionary object. |
Removes an arbitrary item from a Python Dictionary object. |
Built in Functions available for a Python Dictionary object:
Returns the number of items stored in a python dictionary object. |
Determines whether a given key is present in the Python dictionary. |
Determines whether a given key is not present in the Python dictionary. |