Dictionary
A dictionary is a built-in data type in Python that stores a collection of key-value pairs. Each key in a dictionary maps to a corresponding value, allowing you to associate data in a way that's easy to retrieve and manipulate. Dictionaries are also known as associative arrays, hash maps, or hash tables in other programming languages.
Dictionaries are ordered data types which are used to store data values in key:value pairs.
Accessing Items in Dictionary
We can access individual items in a dictionary using keys.
Unique Items
Items in a dictionary must be unique. If you add duplicate items in a dictionary, they will be discarded.
Data types of Dictionary Items
Items in a dictionary can be of same or different data type.
Changing Items in Dictionary
We can also change items in dictionary by referencing to keys.
Adding Items in Dictionary
We can add new items in dictionary by referencing to keys.
Checking if the item exists in a Dictionary
We have two ways to check if the item exists in a dictionary or not.
Nested Dictionaries
If a dictionary contains another dictionary, it is called nested dictionary.
Methods on Dictionaries
| Method | Code | Description |
|---|---|---|
| .clear() | person.clear() | Removes all key-value pairs from the dictionary, effectively emptying the dictionary. |
| .copy() | copied_dict = original_dict.copy() | Creates a shallow copy of a dictionary. |
| .fromkeys() | new_dict = dict.fromkeys(keys, default_value) | Creates a new dictionary with specified keys and an optional default value for those keys. |
| .get() | value_a = myDict.get('a') | Retrieves the value associated with a given key. |
| .items() | items = my_dict.items() | Retrieves a view of the dictionary's key-value pairs as tuples. |
| .keys() | keys = my_dict.keys() | Retrieve a view of the dictionary's keys. |
| .pop() | value_b = my_dict.pop('b') | Removes and returns the value associated with a specified key. |
| .popitem() | key_value_pair = my_dict.popitem() | Removes and returns a key-value pair from the dictionary. |
| .setdefault() | value_a = my_dict.setdefault('a', 10) | Retrieves the value associated with a key, and if the key is not present in the dictionary, it sets a default value for that key and adds it to the dictionary. |
| .update() | my_dict.update(update_dict) | Updates a dictionary with key-value pairs from another dictionary or from an iterable of key-value pairs. |
| .values() | values = my_dict.values() | Retrieves a view of the dictionary's values. |
| dict() | newDict = dict(myDict) | Creates a new dictionary or to convert other data types into dictionaries. |
Practice Exercises
Complete these exercises to reinforce your learning and earn XP