How do you create a dictionary in Python?
Dictionaries in Python are mutable data types that contain
key: value
pairs. A dictionary can be a great way to organise information, especially if checks need to be performed prior for uniqueness and/or the value of that key needs to be changed, skipped or inserted.
Creating A Dictionary
Dictionaries can be created using either the
dict()
constructor method, using the
dict
literal annotation
{}
or using a
dict
comprehension.
Here are examples of how to create a dictionary using each approach and an explanation of when might be the most appropriate time to use this approach.
Create Dictionary Using
dict()
Method
The
dict()
constructor method in Python
is one means of creating a dictionary in Python. The
dict()
constructor can take multiple parameters of
key: value
pairs by assigning parameter names to values, like so:
>>> dict(a=1, b=2)
{'a': 1, 'b': 2}
>>> dict(a='1', b='2')
{'a': '1', 'b': '2'}
Notice this assigns parameter names as the keys and the parameter values as the values in the newly created dictionary.
Create Empty Dictionary Using
dict()
You can also create an empty dictionary using the
dict()
constructor method. Simply leave the parameter of the
dict()
method empty, like so:
>>> a_dict = dict()
>>> print(a_dict)
{}
>>> type(a_dict)
<class 'dict'>
An empty dictionary is the most basic type of dictionary.
Creating Dictionaries From Other Data Types
The
dict()
constructor method can also be used to create
dict
data types from different
compatible
data types such as two-dimensional lists and tuples.
Here is a demonstration displaying how other data types, can be used to create a dictionary in one-line of code using the
dict()
constructor:
>>> a_list = [['a', 1], ['b', 2]]
>>> dict(a_list)
{'a': 1, 'b': 2}
>>> a_tuple = (('a', 1), ('b', 2))
>>> dict(a_tuple)
{'a': 1, 'b': 2}
Besides creating a
dict
data type using other data types, the
dict()
constructor can also be used to create a shallow copy of another dict.
Create Dictionary By Copying Another
There are times when you want to create a new dictionary by copying the contents of another. However, just by assigning a new variable to an existing dictionary variable will not copy it.
What happens when you create a new dictionary variable by assigning it to an existing one?
>>> a_dict = dict(a=1, b=2)
>>> b_dict = a_dict
>>> a_dict['c'] = 3
>>> print(b_dict)
{'a': 1, 'b': 2, 'c': 3}
As you can see from the above output
b_dict
contains the same result as
a_dict
even though
a_dict
was changed
after
it was assigned to
b_dict
.
How can you create a new dictionary from an existing one without having it change after assignment?
One way of creating a new dictionary from an existing one is to use the
dict()
constructor method.
Here’s an example demonstrating how a dictionary can be copied using the built-in
dict()
constructor:
>>> a_dict = dict(a=1, b=2)
>>> b_dict = dict(a_dict)
>>> a_dict['c'] = 3
>>> print(b_dict)
{'a': 1, 'b': 2}
This result is very different from the previous result above. The
b_dict
variable
did not change
when the original
a_dict
changed after assignment.
While there still are some caveats when using this approach, if the values for your keys inside your dictionary are immutable, then this could be an easy method to create a new copy from an existing
dict
variable.
Problems With Using
dict()
Constructor
You may encounter issues when using the
dict()
constructor method. Some common errors occur when constructing a dictionary from a string or number.
Here are some common
ValueError
and
TypeError
issues you may experience when trying to construct a dictionary using the
dict()
constructor method:
>>> dict("{'a': 1}")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> dict(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> dict(1.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not iterable
>>> dict({1, 2, 3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence
The errors displayed inform the user of the problems you will have when trying to use strings, numbers, and even sets and converting them to dictionary data types with the
dict()
constructor method.
Create Dictionary Using Dict Literal
{}
Another way to create a dictionary is to use the literal annotation
{}
. The same can be used when creating a dictionary by just using the literal notation
{}
, as shown here:
>>> b_dict = {'a': 2}
>>> print(b_dict)
{'a': 2}
>>> type(b_dict)
<class 'dict'>
This is no different to creating a dictionary using the
dict()
constructor method and is a shorthand approach of doing so.
Create An Empty Dictionary
If you need to initialise a variable as a dictionary data type, you can use the
dict
literal approach by assigning that variable to an empty
dict
literal.
An example of what this looks like is shown below:
>>> a_dict = {}
>>> type(a_dict)
<class 'dict'>
As you can see from the above Python REPL the empty
dict
literal created a new
dict
object.
It can be an easy way to create a new dictionary in Python as it only requires two characters instead of the six to type
dict()
, however, if it makes the code difficult to reason with then it may be better for the more explicit
dict()
constructor.
Create A Dictionary Using Dict Comprehension
One other method to create a
dict
data type is through a dict comprehension.
A dict comprehension loops through an iterable object assigning keys and values according to the construction of the comprehension.
For example, if you have a single dimension list and want to transpose this into a
dict
object you cannot use the
dict()
constructor:
>>> a_list = ['Jan', 'Feb', 'Mar']
>>> a_dict = dict(a_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
This problem cannot be solved even with the
dict
literal syntax, so how can this be done?
Enter the dict comprehension .
With a dict comprehension you can loop through your iterable and assign the keys and corresponding values according to how you want to create your new dictionary.
The dict comprehension has the following basic syntax:
{key: value for x in iterable_object}
Using the list in the previous example, this would look a little something like this:
>>> a_list = ['Jan', 'Feb', 'Mar']
>>> a_dict = {x: idx for idx, x in enumerate(a_list)}
>>> print(a_dict)
{'Jan': 0, 'Feb': 1, 'Mar': 2}
Using a for loop with an index
idx
helps to assign the abbreviated months of the year to index numbers.
A dict comprehension can help create a dict data type when handling more complex iterable objects.
Key Constraints
Each entry in the dictionary is a single element composed of both the key (the item before the colon) and its value (the item after the colon). The value can be any data type, such as an integer, string, or even another dictionary, but the key has a couple of conditions.
The conditions when adding a
key: value
pair into a dictionary are:
- The key must be unique; and
- The key must be immutable.
Keys Need To Be Unique
What happens when you instantiate a
dict
using the
dict()
or
dict
literal syntax to create a new dictionary?
Have a look at the following results:
>>> a_dict = dict(a=1, a=2)
File "<stdin>", line 1
SyntaxError: keyword argument repeated: a
When using the
dict()
constructor method a
SyntaxError
is produced when assigning two items with the same key.
What happens when you create a dictionary using the
dict
literal syntax?
>>> dict({'a': 1, 'a': 2})
{'a': 2}
As observed from the Python REPL if a dictionary is constructed using the
dict
literal approach and their contains within the
dict
literal the same key more than once, like
{'a': 1, 'a': 2}
, the
last value
in the dictionary is preserved.
Notice that no
SyntaxError
is produced as it did with the
dict()
constructor method.
To be clear, you
can
use the same
key
multiple times throughout a dictionary – however, it must be unique on its own branch. The following example demonstrates that multiple nested dictionaries having the same key are okay:
>>> dict({'a': {'a': {'a': 1}}})
{'a': {'a': {'a': 1}}}
Keys Need To Be Hashable (Immutable)
The value of the key must also be immutable , which means that the key is hashable . You may have come across other data types in Python which are immutable, and these are things like: numbers, strings, tuples (etc).
A key can be of an immutable data type, but cannot be of a mutable data type.
Common examples of a mutable data type include lists and dictionaries.
What happens when you try to create a key that is mutable:
>>> dict({[1]: 1})
Traceback (most recent call last):
File "", line 1, in
TypeError: unhashable type: 'list'
As you can see, the error from the Python REPL is that the list used as the key is of an
unhashable type
. As the error states, a list object cannot be hashed as it can be changed throughout its life (a list can get larger or smaller), whereas a
tuple
object is static and its contents are fixed – therefore it is
hashable
:
>>> a_list = [1, 2, 3]
>>> hash(a_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> a_tuple = (1, 2, 3)
>>> hash(a_tuple)
529344067295497451
Using the
hash()
function above can help to determine whether an item can be used as a key in your dictionary.
Here are some examples of using an immutable data type, like a
tuple
, as a key in a dictionary:
>>> a_dict = {(1, 2, 3): 100}
>>> type(a_dict)
<class 'dict'>
>>> a_dict[(1, 2, 3)]
100
Summary
How do you create a dictionary in Python? Creating a dictionary in Python can be done in one of three ways: using the
dict()
constructor method, the
dict
literal syntax or the
dict
comprehension syntax.
Using the
dict()
constructor approach can be helpful when converting existing data types that can readily be converted into dictionaries, or if working with fixed key parameters and dynamic values.
The
dict
literal approach is easy and can be useful if duplicate keys are likely and no errors want to be thrown.
Finally,
dict
comprehensions are helpful when working with iterables that cannot readily be converted into dictionaries using the
dict()
constructor approach.