Introduction
This article is in continuation of the article series “Jump Start with Python”. To read the previous articles, please refer to the links, given below:
Now, let’s start with part eight of this article series. Today, we will be discussing the dictionaries in Python.
Dictionary is an abstract data type, composed of a collection of key-value pairs enclosed within the braces, where a key is immutable and must be unique. A dictionary is an unordered collection and is mutable in nature. It can contain mixed types, as the keys and their corresponding values.
Python accounts for the dictionary under
mapping types. Dictionaries are also called the hash tables or associative arrays. Below is a simple example of a Python dictionary:
Creating a Dictionary
A dictionary in Python can be created in two different ways:
- Just enclose (key, value) pairs between the braces.
Syntax: dict_name={ “key1”: “val”, “key2”: “val”, “key3”: “val”, —, “keyn”: “val” }
- Using dict constructor.
Syntax: dict_name=dict(key1=“val”, key2=“val”, key3=“val”, —, keyn=“val”).
Some Facts About Dictionary
- A dictionary without any positional argument is called an empty dictionary.
- A dictionary is an unordered set of the keys, value pairs and is indexed, using the keys specified in it.
- The keys in a dictionary are unique and if multiple assignments to a key are attempted, the latter value will be assigned to the respective key discarding the value, previously assigned to it.
Sub-Dictionaries
A dictionary in Python can have the dictionary as the elements. These sub-dictionaries may further contain the dictionary elements as well. Dictionary can be recursively created by many sub-dictionary structures. Below is a syntax for the sub-dictionary in Python.
Syntax:
dict_name={“keya”: {“key1”: “val”, “key2”: “val”, --- , “keyn”: “val”}, “keyb”: { --- }, “keyc”: { --- }, --- , “keyd”: { --- }}
Below is a simple example for the sub-dictionary in Python:
Basic Operations
- Accessing a Dictionary
As discussed above, the dictionaries store the data in the form of key-value pairs and in order to access a value element, you need its key. Here is the syntax to access the dictionary element.
Syntax: dict_name[‘key']
- Updating a Dictionary
A dictionary can be updated or a new key-value pair can be added to it by directly assigning a value to the key and the key-value pair is updated or added to the dictionary.
Syntax: dict_name[‘key’]: value
- Deleting Dictionary Elements
Dictionary elements can be deleted, using del statement, followed by the key of the element to be deleted.
Syntax: del dict_name[‘key']
- Deleting a Dictionary
A dictionary can be deleted, using del statement, followed by the name of the dictionary.
Syntax: del dict_name
Dictionary Methods & Functions
- Length
This function is used to determine the number of the key-value pairs (elements) present inside a dictionary. It consists of one parameter and it is explained, as given below:
dict_name: It is the dictionary, whose length is to be determined.
Syntax: len(dict_name)
- String
This function is used to flatten the dictionary into a printable string representation. It consists of one parameter and it is explained below:
dict_name: It is the dictionary, which is to be converted into a string.
Syntax: str(dict_name)
- Clear Method
This method is used to clear or remove all the key-value pairs in a dictionary.
Syntax: dict_name.clear()
- Pop Method
This method is used to remove a key from a dictionary and return a value for that key. It consists of the two parameters and they are explained below
key: It is a key-value pair element, which is to be removed from the dictionary.
val: It is optional and is used to specify the value if the key is not found, else KeyError is raised.
Syntax: dict_name.pop(key, val)
- Pop Item Method
This method is similar to Pop method, discussed above. It is used to remove and return an arbitrary key-value pair from the dictionary. It will raise a KeyError, once the dictionary is empty and does not have any elements in it.
Syntax: dict_name.popitem()
- Copy Method
This method is used to make a copy of the dictionary into another dictionary variable.
Syntax: dict_copy_var = dict_name.copy()
- From Keys Method:
This method returns a new dictionary with the keys taken from specified iterable and value set to the specified value. It consists of the two parameters and they are explained below:
iterable: It is a list of all the values, which will be used as the keys in the dictionary, being prepared.
value: It is a value for each key, specified in the iterable and is optional in nature. If no value is specified, the default value is taken, which is 'None'.
Syntax: dict_name.fromkeys(iterable, value)
- Get Method
It is a content access method and is used to return a value for the key specified from the dictionary. If the key is not available, it returns the default value i.e. `None`. It consists of the two parameters and they are explained below:
key: It is a required parameter and is a key, whose value will be returned by the method.
default: It is an optional parameter and returns this value when the key is not found.
Syntax: dict_name.get(key, default)
- Items Method
It is a content access method and returns all the key-value pairs of the dictionary as a list.
Syntax: dict_name.items()
- Keys Method
It is a content access method and returns all the keys available in a dictionary as a list.
Syntax: dict_name.keys()
- Values Method
It is a content access method and returns all the values available in a dictionary as a list.
Syntax: dict_name.values()
- Update Method
This method is used to add the key-value pairs to an existing dictionary. It consists of one parameter and it is explained below:
mapping: It is key-value pairs to be added to the existing dictionary. It is a required parameter and can be either another dictionary object or iterable key-value pairs.
Syntax: dict_name.update(mapping)
Looping in Dictionary
Python allows looping through the dictionary, using
for keyword. Domain dictionary can be traversed to print the keys, values or both keys as well as the values for the elements in the dictionary. Here's how it is done:
- Looping Through All The Keys in the Dictionary:
- Looping Through All The Values in the Dictionary:
- Looping Through Both the Keys & Values in the Dictionary: