Python Dictionaries

Nwani Ugonna Stanley
The Startup
Published in
3 min readFeb 10, 2021
Photo by Joshua Hoehne on Unsplash

Dictionaries are data structures that store data in key-value pairs. Unlike lists, tuples or sets that store only a value, a dictionary needs two values, a key and a value. It is written as key: value. The value can be printed out by calling the key name.

>>> fruits = {'apple': 'red', 'banana': 'green', 'cherry': 'red'}
>>> type(fruits)
<class 'dict'>
>>> fruits['apple']
'red'

Summary on Python Dictionaries

  1. Dictionaries are enclosed in curly brackets {}. An empty dictionary can be created by using the function dict() or just the curly brackets.
>>> dict1 = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
>>> type(dict1)
<class 'dict'>
>>> dict2 = {}
>>> type(dict2)
<class 'dict'>
>>> dict3 = dict()
>>> type(dict3)
<class 'dict'>

2. There should not be duplicate keys in one dictionary. If you have a dictionary with the same keys, the most recent value associated with that key is returned.

>>> fruits = {'apple': 'red', 'banana': 'green', 'grape': 'green'}
>>> material = {'biro': 'red', 'pencil': 'grey', 'biro': 'blue'}
>>> material['biro']
'blue'

Things can get confusing if there are duplicate keys in a dictionary.

3. The keys in a dictionary are of hashable type. That is they are made up of objects that does not change during its lifetime. Mutable objects like lists cannot be used as a key in a dictionary. Tuples can be used as keys because they are immutable.

>>> dict4 = {('a', 'b'): 'tuple', 'string': 'ball', 1: 'integer'}
>>> dict4
{('a', 'b'): 'tuple', 'string': 'ball', 1: 'integer'}
>>> dict5 = {[1, 2, 3]: 'list1'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Strings and integers are also of hashable type so they can be used as keys in a dictionary. Values in a dictionary can be mutable or immutable.

4. Python dictionaries are ordered data structures. If your python’s version is 3.7 and above, dictionaries are ordered, if your python’s version is below 3.7, any dictionary you create will be unordered.

>>> dict6 = {'name': 'James', 'age': 20, 'address': 'California'}
>>> dict6
{'name': 'James', 'age': 20, 'address': 'California'}

You can check your python version by opening your command prompt and typing python and pressing the Enter key. That is if you have python installed on your PC.

Command prompt

5. Python dictionaries does not allow duplicates. Like sets, if a key: value pair is written two or more times, only one of them gets printed out.

>>> dict7 = {'name': 'James', 'age': 20, 'age': 20}
>>> dict7
{'name': 'James', 'age': 20}

Conclusion

Dictionaries have a lot of use cases in python. To get the list of all the methods that python dictionaries allow, type help(dict) in your command prompt after loading python.

Thanks for reading:).

--

--