Everything about dictionaries in Python | Nouman | Towards Data Science

Dictionaries in Python, or hash tables in other programming languages, are one of the most efficient data structures for storing and retrieving values. They store each value against a key making a key-value pair. In this article, we will be learning everything that one should know about dictionaries to get started in Python.
Here’s a list of topics we will be covering regarding dictionaries today:
Intro to Dictionaries
How to define a dictionary
How to access a dictionary
How to assign values in a dictionary
Methods on Dictionaries
Restrictions on Dictionary Keys/Values
Conclusion
This is part of my 30-Day Article Writing Challenge. Feel free to check out the articles on my pledge post:
nouman10.medium.com
Dictionary is a compound data structure in Python that basically consists of a list of key-value pairs. Each key in a key-value pair maps that key to its associative value.
Dictionaries are generally defined in Python by a list of comma-separated key-value pairs wrapped around curly braces ({}). Each key is separated from its associated value by a colon (:).
The following code snippet constructs a dictionary of football players and their associated clubs:
football_players_club = {      "Cristiano Ronaldo": "Juventus",      "Bruno Fernandes": "Manchester United",      "Lionel Messi": "Barcelona",      "Sadio Mane": "Liverpool",      "Harry Kane": "Tottenham Hotspur"}
You can also define a dictionary by using its constructor, dict() . It can accept a collection of key-value pairs. So, a list containing tuples of key-value pairs is a valid way to construct a dictionary through its constructor and so is a tuple containing lists of key-value pairs.
Although you can display a dictionary the same way you would do a list, you can’t access them using a numerical index. There is no order in a dictionary and you can only access a value using its key. Using an index would result in a KeyError .
In order to access dictionary values, we use the keys associated with the values. For instance, to access “Barcelona” and “Liverpool” in the above dictionary we use:
print(football_players_club["Lionel Messi"])print(football_players_club["Sadio Mane"])
Using a key that is not present in the dictionary results in a KeyError :
football_players_club['Muhammad Salah']football_players_club[1]
These both result in the following errors:
Note that although we are using a numerical index in the second example, the error is the same for both. This is because Python considers whatever you pass inside the square brackets as a key to the dictionary. In fact, Python actually allows dictionaries to have numerical keys like follows:
numerical_keys = {   1: 'a',   0: 'b',   4: 'c'}numerical_keys[0]
When we use “0” as the key, we are not saying to get the value at the index 0 rather the value having 0 as the key and that is “b” as expected.
We can assign new values to a key or even update the values of existing keys in a dictionary by simply accessing the dictionary with the key and setting it to the desired value like this:
football_players_club['Luis Suarez'] = 'Athletico Madrid'football_players_club['Harry Kane'] = 'Manchester City'
Here we will look into some of the common methods applied to dictionaries in python and at the end, we will see a demo for all these together:
Note: dict , dict_1 , dict_2 all represent some kind of arbitrary dictionaries.
As the name suggests, it returns the length of the key-value pairs in a dictionary.
Syntax: len(dict)
It allows us to check whether a key exists inside a dictionary or not
Syntax: key in dict
We can make use of this to avoid accessing a key that is not present in a dictionary. For instance, using dict[key] will raise a KeyError if the key is not present inside the dictionary but using the following line of code will not as python short-circuit evaluation will prevent it from evaluating the second part of the and statement in case the key in dict returns false.
key in dict and dict[key]
It gets the value associated with the given key. It also accepts a optional default argument which is returned in case the key is not present in the dictionary. Although, if the key is not present and the default value is not passed as well, the function returns None.
Syntax: dict.get(key) or dict.get(key, default_value)
It returns the keys of the dictionary
Syntax: dict.keys()
It returns the values of the dictionary
Syntax: dict.values()
It returns the items of the dictionary as a sequence of key-value tuples.
Syntax: dict.items()
Note: Using for loop with a dictionary returns the key at every iteration i.e, for key in dict will iterate through the list of keys inside the dictionary
It removes the last key-value pair from the dictionary and returns that.
Syntax: dict.popitem()
It removes the key-value pair associated with the given key. It also accepts a optional default argument which is returned in case the key is not present in the dictionary. Although, if the key is not present and the default value is not passed as well, the function raises a KeyError.
Syntax: dict.pop(key) or dict.pop(key, default_value)
As the name suggests, it clears the dictionary(empties it)
Syntax: dict.clear()
It merges a dictionary with another dictionary or with an iterable of key-value pairs as we saw in the defining a dictionary section. All the key-value pairs in both the dictionaries are added to the first dictionary. If a key is already present in the first dictionary, its value is updated by the value associated with the key in the second dictionary. If a key is not present in the first dictionary
Syntax: dict_1.update(dict_2) (Note: Only dict_1 is updated)
As we saw before, you can set strings and integers as keys in dictionary values. You can even set the built-in objects in Python as the keys as well like this:
dictionary = { int: 8, float: 9 }dictionary[str] = 10print(dictionary)
However, there are some rules as well. A given key can only appear once in a dictionary i.e, every attempt to set a value to an already stored key in a dictionary will simply override the previous value. The most recent one is the value stored.
Also, you can only use immutable types as keys. That means while tuples make a perfectly good key, lists on the other hand do not.
dictionary = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}print(dictionary)
This runs perfectly but the following gives an error:
dictionary = {[1, 1]: 'a'}print(dictionary)
On the other hand, dictionary values have no restrictions at all. Any value is a suitable dictionary value whether it is mutable or immutable, built-in or user-defined. Dictionary values can be repeated as well, as many times as you want.
To conclude:
We started with a basic introduction to dictionaries in Python which included defining, accessing and assigning values to them
Then we looked into some built-in methods for dictionaries
Finally, we looked into the restrictions of dictionary keys and values.
If you feel that above content was useful for you, do share it and feel free to support me ->