Python Dictionary is one of the primitive data structures provided by Python that comes built-in. Python Dictionary consists of two values, a key and a value where the key must be unique and hashable to access the value of the respective key in the dictionary. Python Dictionary is an implementation of a data structure known as associative array.
Why do we use a Python Dictionary?
A dictionary comes in handy when we have to store or manipulate data and create complex data mappings with its use as a nested data structure with efficient operations. It is helpful in mapping a key to its value that can be accessed in constant time which gives it an edge over the list in terms of searching or retrieving the value for a particular key.
Creating a Python Dictionary
Dictionaries can be created in Python using several ways with the most often used being opening and closing curly braces. We can store values in the dictionary upon its creation where the key and value are separated using a colon (‘:’) with the values being separated by a comma (‘,’). An example can be detailed as:-
Syntax 1 for creating a python dictionary:
languages = {
"key1": value1,
"key2": ,value2
"key3": value3,
"key4": value4
}
Another valid way to create a dictionary is by using the dict() method where the built-in constructor creates a dictionary upon interpreting it.
Syntax 2 for creating a python dictionary:
dict = dict(key1='value1', key2='value2')
Dictionary Comprehension is another but slightly complex way to create a dictionary where an iterator is performed inside to store the key-value pairs in a similar technique to how it is implemented with List Comprehension.
Syntax 3 for creating a python dictionary:
dict = {key: value for key, value in (('key1', 'value1'), ('key2', 'value2'))}
Now that we have a clear idea on how to create a dictionary, we will move forward to study how manipulations can be made on a Python Dictionary.
Accessing a Python Dictionary
Dictionaries in Python can be accessed such that we must provide a key to access the value such as in the given example, a Python Dictionary named languages will have a key named Python, whose value will be printed. In case, the key is not present in dictionary then an error will be thrown:-
Syntax for accessing single value with the given key of python dictionary:
print(languages["Python"])
print(languages.get("Python"))
In case, we want to access all the elements of the dictionary, inclusive of key and value, then the item() method can be called to access the elements. A for loop can be handy in doing so as given given below:-
Syntax for accessing key value pair of python dictionary:
for key, value in languages.items():
print(f"{key} was created in {value}")
Manipulating Dictionary in Python
Having studied how to create and read a dictionary in python, let’s move onto the techniques we resort to while updating and deleting the keys lying inside the dictionary. To insert a key, we can either place the key inside square brackets with the name of the dictionary and assign the value to it.
Syntax for manipulating the value of given key:
languages[key] = value
Also, we can use the update function to insert a keys with its subsequent values, that can be mentioned as follow:-
languages.update({"Python": 1})
As far as deleting a key from the dictionary is concerned, the operation can be performed with the del or pop method.
Syntax for deleting a key value pair:
languages.pop("Python")
del languages["Python"]
Types of Dictionaries in Python
The power of dictionaries is not limited to these as there are fancy dictionaries that can be imported for their various required use cases. Collection library has various dictionaries like Counter and defaultdict that are used as a tool for problem-solving.
1. Defaultdict
It is a subclass of the general python dictionary and it has a default value for a key in case the key is not found in the dictionary. On creating a defaultdict, we pass the default value, whether we need it to be 0 (int) or an empty list (list). Here is an example with output printed in.
Code for Defaultdict:
from collections import defaultdict d = defaultdict(int) d['a'] = 1 d['b'] = 2 print(d['c']) print(d)
Output:
0
defaultdict(, {'a': 1, 'b': 2, 'c': 0})
2. Counter
It is a special type of dictionary that works as a counter of keys present in the dictionary. It keeps counting the number of elements present in an iterable to store them as a key with their frequency.
Code for Counter:
from collections import Counter c = Counter([1, 2, 2, 3, 4, 4, 4]) print(c)
Output:
Counter({4: 3, 2: 2, 1: 1, 3: 1})
3. OrderedDict
Another form of dictionary where the order of the elements inserted in the dictionary remains the same. After deleting and reinserting the same element, the element will be positioned in the sequence of insertion. Here is an example code to help the working of OrderedDict better.
Code for OrderedDict:
from collections import OrderedDict d = OrderedDict() d['a'] = 1 d['b'] = 2 print(d)
Output:
OrderedDict([('a', 1), ('b', 2)])
4. ChainMap
It is a specialized form of dictionary present in collections library that merges two or more dictionaries into one single dictionary.
Code for ChainMap:
from collections import ChainMap dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} chain = ChainMap(dict1, dict2) print(chain) print(chain['a']) print(chain['c']) print(list(chain.keys()))
Output:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
1
3
['c', 'd', 'a', 'b']
Conclusion
In this article, we studied what a python dictionary is and learnt how we can create, read, update and delete in a dictionary by implementing it in Python Programming Language. We came across all the important methods that we can use to manipulate a dictionary. In the later section, we studied the different types of dictionaries apart from the usual and how we can use them in our program.
We hope you liked this article on How to use a Python dictionary and hope to see you again at PrepBytes with another informative article.
Frequently Asked Questions
1. Can we access keys and values of a dictionary separately all at once?
Yes, we can access all the keys using the keys() method and all the values at once by the values() method. If we want to access both, we can use the items() method.
2. Are dictionaries like defaultdict and Counter a built-in constructor in Python like dict()?
No, we need to import collections to use these modified python dictionaries like Counter and defaultdict.
3. What do you mean by dictionary?
A dictionary is a data structure in python that allows storing key-value pairs where a unique key is mapped to a value.