What is dict in python 3?
The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are: class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Note: **kwarg let you take an arbitrary number of keyword arguments.
When you create a dictionary in Python 3, its syntax consists of a key-value pair in a mapped arrangement. You can create a Python dictionary in several ways. The sections below show you the different ways to create a Python dictionary. Each method has a use case in which it works best. A Python dictionary supports the use of tuples for keys. It’s also possible to define a dictionary using a dictionary comprehension to make the code significantly shorter.
A dictionary always has a key that relies on an immutable type, such as: int, float, decimal, string, tuple, and range. Typically, you use the same data type for all of a dictionary’s keys. However, a single dictionary can contain keys of different immutable types and its values can be of any type. For example:
If you print the value of the numbers dictionary created above, you see the following output:
As demonstrated above, dictionaries consist of the following syntax:
The example dictionary additionally does the following:
A dictionary can mix immutable data types in the keys. This means that the following dictionary is also acceptable:
However, accessing dictionary keys is much harder when using mixed data types.
You can create a Python dictionary using the dict() constructor and a sequence of key-value pairs.
Printing the numbers dictionary results in the following output:
The examples below use the dict() constructor to create dictionaries using a variety of data types as keys and values. The example demonstrates that it’s unnecessary, in many cases, to convert your data’s format before creating a dictionary.
Printing the numbers dictionary results in the following output:
The example below shows that you can mix and match dictionary creating methods. It uses the dict() method to create the numbers dictionary. The numbers dictionary’s first entry consists of another dictionary that is declared using the curly braces syntax. Mixing dictionary creating methods is especially useful when the data you’re working with appears in more than one form.
Printing the numbers dictionary results in the following output:
A tuple is a built-in Python data structure that stores multiple comma-separated values. Tuples as dictionary keys are often used to store point coordinates used in maps or other applications that require coordinate data. For example, use a tuple to store a first and last name that maps to a telephone number. The example dictionary map_coordinates uses a tuple as its keys.
To learn more about the syntax of Python tuples and other topics, like built-in tuple methods, and tuple unpacking, see our guide An Introduction to Python Tuples.
A dictionary comprehension creates a new dictionary and populates its keys or values based on an expression. The typical syntax for a dictionary comprehension is as follows:
For example, the following dictionary comprehension uses the numbers 0 through 9 as keys and the squared values of those keys for values:
Printing the squared_dict dictionary comprehension displays the dictionary that was created with the dictionary comprehension:
Output:
In addition to using an expression for the values, you can also use expressions to generate a dictionary’s keys. For example, the following dictionary comprehension defines a dictionary with the characters A through J as keys:
Printing the example_dict dictionary comprehension displays the following dictionary:
Output:
While dictionary comprehension generates the keys and values, the dictionary itself acts like any other Python dictionary.
Dictionary comprehensions require less typing due to its concise syntax. It also reduces the chance of errors and if written simply, it keeps your code more readable.
After creating a dictionary, you can access its values in several different ways. The two common methods for performing this task are to access the value directly or to access it as part of a loop. A dictionary often contains unwanted values, so using Python comprehensions can cut the dictionary down to size before you access its values. These techniques appear in the following sections.
If you are newer to for and while loops in Python, you can view several examples in our guide For and While Loops in Python 3.
To provide access to its values, a dictionary relies on keys, not numeric indexes. When a dictionary uses well-defined keys, it is much easier to understand what type of data is stored in the dictionary.
The syntax for accessing a dictionary value using its key is as follows:
Using the numbers dictionary from the beginning of this guide, you can access the value of key One as shown below:
When you print example_var, the value of the 'One' key is returned, i.e., 1:
Output:
If you attempt to access a non-existent key from a dictionary, Python outputs a KeyError exception. This exception often happens when the key specified uses a different spelling or different case than the original key. For example, if you try to access the 'one' key, instead of the 'One' key, you receive a KeyError exception:
The KeyError exception is raised because the key is case-sensitive. To avoid this error, it’s possible to add code similar to the example below to validate the key:
Python dictionaries have built-in support for iterating over its keys. To iterate over a Python dictionary and access all its keys, use a for loop:
This generates the following output:
If you’d like to access a dictionary’s values instead of keys, modify the for loop as follows:
This generates the following output:
Python provides several built-in methods that support accessing dictionary keys and values.
Using the built-in methods listed above, you can iterate over a dictionary’s keys and values using the following for loop:
Your output should resemble the following:
You may need to create a new dictionary based on the keys and values from another dictionary. For these cases, Python comprehensions are very useful. For example, the comprehension below selects certain keys based on specific criteria.
The example code obtains the key-value pairs in the numbers dictionary using the items() method. Then it verifies whether the first character of the key is a T. If it is, then the key-value pair appears in a tuple that is then used to create a new dictionary using the dict() method.
The example below demonstrates the syntax to add a new key-value pair to an existing Python dictionary.
To add a new key-value pair to the numbers dictionary used throughout this guide, use the following code:
You can also modify an existing dictionary value. You should ensure that the value you are modifying actually exists in the dictionary. For this reason, the following code is a safe approach:
This code is safer because it uses the if clause to make sure the updated value is added to your dictionary only if the key One exists. Without the if clause, if the key One did not exist, you would unintentionally add a new entry to the numbers dictionary.
There are various ways to delete a dictionary value in Python. The first method is using the del keyword followed by the key that stores the value you want to delete.
When you use the del keyword, Python does not return the modified dictionary. This makes it difficult to know how the operation affected the existing dictionary. A safer method of removing values from a dictionary is to use the pop() method, as shown below:
This version of the code has several advantages, one of which is that the pop() method returns the value that is removed from the dictionary. This enables you to store the value in a variable. The second advantage is that pop() is clearer in its intent. Similarly, storing the value in a variable enables you to add the value back to your dictionary, if needed.
If you need to remove the last value from a dictionary, use the popitem() method instead. The function returns both the key and the value from the dictionary.
Since the key and the value are both returned, it’s possible to recover from an accidental removal. You can also let the user know precisely what was removed from the dictionary.
Python also makes it possible to clear the dictionary entirely using the clear() method. In this case, the method doesn’t return anything, so the only recovery option is to make a copy of the dictionary before clearing it.
To find the length of a dictionary in Python, use the len() method, as follows:
The dictionary is an unordered collection that contains key:value pairs separated by commas inside curly brackets. Dictionaries are optimized to retrieve values when the key is known.
The following declares a dictionary object.
Above, capitals is a dictionary object which contains key-value pairs inside { }. The left side of : is a key, and the right side is a value. The key should be unique and an immutable object. A number, string or tuple can be used as key. Hence, the following dictionaries are also valid:
However, a dictionary with a list as a key is not valid, as the list is mutable:
But, a list can be used as a value.
The same key cannot appear more than once in a collection. If the key appears more than once, only the last will be retained. The value can be of any data type. One value can be assigned to more than one key.
The dict is the class of all dictionaries, as shown below.
A dictionary can also be created using the dict() constructor method.
Dictionary is an unordered collection, so a value cannot be accessed using an index; instead, a key must be specified in the square brackets, as shown below.
Use the get() method to retrieve the key's value even if keys are not known. It returns None if the key does not exist instead of raising an error.
Use the for loop to iterate a dictionary in the Python script.
As mentioned earlier, the key cannot appear more than once. Use the same key and assign a new value to it to update the dictionary object.
Use a new key and assign a value to it. The dictionary will show an additional key-value pair in it.
Use the del keyword, pop(), or popitem() methods to delete a pair from a dictionary or the dictionary object itself. To delete a pair, use its key as a parameter. To delete a dictionary object, use its name.
The NameError indicates that the dictionary object has been removed from memory.
The keys() and values() methods return a view objects containing keys and values respectively.
You can check whether a paritular key exists in a dictionary collection or not usng the in or not in keywords, as shown below. Note that it only checks for keys not values.
Let's assume there are three dictionary objects, as below:
Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll number as key and the above dictionaries at their value.
The student object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as values to keys 1, 2, and 3, respectively. The students[1] returns d1.
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −
When the above code is executed, it produces the following result −
If we attempt to access a data item with a key, which is not a part of the dictionary, we get an error as follows −
When the above code is executed, it produces the following result −
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown in a simple example given below.
When the above code is executed, it produces the following result −
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −
This produces the following result.
An exception is raised because after del dict, the dictionary does not exist anymore.
Note − The del() method is discussed in subsequent section.
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate keys are encountered during assignment, the last assignment wins. For example −
When the above code is executed, it produces the following result −
(b) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example −
When the above code is executed, it produces the following result −
Python includes the following dictionary functions −
Python includes the following dictionary methods −
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
Dictionaries cannot have two items with the same key:
To determine how many items a dictionary has, use the len() function:
The values in dictionary items can be of any data type:
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
It is also possible to use the dict() constructor to make a dictionary.
There are four collection data types in the Python programming language:
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.